Solarion
Honorary Master
- Joined
- Nov 14, 2012
- Messages
- 28,051
- Reaction score
- 17,804
I just feel like there is a lot of reinventing the wheel going on
want validation errors? .NET already supports that nicely.
want to handle unexpected exceptions in your controllers? .NET already provides hooks to handle them and return a consistent response, without handling them in every controller method
True that. I have just found a segment on global error handling. Could probably leave out the whole catch block entirely now.
C#:
public class ExceptionMiddleware
{
private readonly RequestDelegate next;
private readonly ILogger<ExceptionMiddleware> _logger;
public ExceptionMiddleware(RequestDelegate next, ILogger<ExceptionMiddleware> logger)
{
this.next = next;
_logger = logger;
}
public async Task Invoke(HttpContext context)
{
try
{
await next(context);
}
catch(Exception ex)
{
_logger.LogError(ex, ex.Message);
context.Response.StatusCode = 500;
await context.Response.WriteAsync("An unexpected error occurred. Please try again later.");
}
}
}