Minifycode 2022-05-18 Viewed 544 times ASP.Net Core MVC

In this article, you will learn, how to handle errors in middleware C# Core?.

Our middleware will trigger the catch block and call the HandleExceptionAsync method.

public class ExceptionMiddleware
   private readonly RequestDelegate _next;
   private readonly ILoggerManager _logger;
   public ExceptionMiddleware(RequestDelegate next, ILoggerManager logger)
      _logger = logger;
      _next = next;
   public async Task InvokeAsync(HttpContext httpContext)
            await _next(httpContext);
      catch (Exception ex){
         _logger.LogError($"wrong: {ex}");
         await HandleExceptionAsync(httpContext, ex);


private Task HandleExceptionAsync(HttpContext context, Exception exception)
      context.Response.ContentType = "application/json";
      context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
      return context.Response.WriteAsync(new ErrorDetails(){
         StatusCode = context.Response.StatusCode,
         Message = "Internal Server Error from custom middleware."

Our ExceptionMiddlewareExtensions class with another static method.

public static void ConfigureCustomExceptionMiddleware(this IApplicationBuilder app)

use below method in the Configure method in the Startup class:-


How to handle errors in middleware C# Core?
minify code