In this article, you will learn, how to handle errors in middleware C# Asp.net 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)
{
try{
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."
}.ToString());
}
}
Our ExceptionMiddlewareExtensions class with another static method.
public static void ConfigureCustomExceptionMiddleware(this IApplicationBuilder app)
{
app.UseMiddleware<ExceptionMiddleware>();
}
use below method in the Configure method in the Startup class:-
app.ConfigureCustomExceptionMiddleware();
How to handle errors in middleware C# Asp.net Core?
minify code