Create a new folder named CustomExceptionMiddleware and a class ExceptionMiddleware.cs is inside.
The first thing we need to do is register the IloggerManager service and Implement RequestDelegate through dependency injection.
The _next parameter of the RequestDeleagate type is a function delegate that can be processed Our HTTP request.
After the registration process, we need to create the InvokeAsync() method RequestDelegate cannot handle requests without it.
_next delegate should handle our controller's request and Get operations should generate a successful response. But if the request fails (and it does fail, Since we are forcing an exception),
our middleware will trigger the catch block and call 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){ try{ await _next(httpContext); } catch (Exception ex){ _logger.LogError($"Something went 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 the custom middleware." }.ToString()); } }
Modify our ExceptionMiddlewareExtensions class with another static method −
public static void ConfigureCustomExceptionMiddleware(this IApplicationBuilder app){ app.UseMiddleware<ExceptionMiddleware>(); }
Use this method in the configuration method of the Startup class -
app.ConfigureCustomExceptionMiddleware();
The above is the detailed content of How to handle errors in middleware C# Asp.net Core?. For more information, please follow other related articles on the PHP Chinese website!