Add custom message support to exception handling middleware

This commit is contained in:
martinshoob 2025-08-12 07:51:16 +02:00
parent 84e6f7e2c9
commit dffa410c71

View file

@ -30,10 +30,9 @@ public class ExceptionHandlingMiddleware
private async Task HandleExceptionAsync(HttpContext context, Exception exception) private async Task HandleExceptionAsync(HttpContext context, Exception exception)
{ {
_logger.LogError(exception, "An unexpected error occurred."); _logger.LogError(exception, "An error occurred.");
var defaultResponse = exception switch
var response = exception switch
{ {
BadRequestException _ => new ExceptionResponse(StatusCodes.Status400BadRequest, "Application exception occurred."), BadRequestException _ => new ExceptionResponse(StatusCodes.Status400BadRequest, "Application exception occurred."),
NotFoundException _ => new ExceptionResponse(StatusCodes.Status404NotFound, "The request key not found."), NotFoundException _ => new ExceptionResponse(StatusCodes.Status404NotFound, "The request key not found."),
@ -45,6 +44,12 @@ public class ExceptionHandlingMiddleware
_ => new ExceptionResponse(StatusCodes.Status500InternalServerError, "Internal server error. Please retry later.") _ => new ExceptionResponse(StatusCodes.Status500InternalServerError, "Internal server error. Please retry later.")
}; };
var description = !string.IsNullOrWhiteSpace(exception.Message)
? exception.Message
: defaultResponse.Description;
var response = defaultResponse with { Description = description };
context.Response.ContentType = "application/json"; context.Response.ContentType = "application/json";
context.Response.StatusCode = response.StatusCode; context.Response.StatusCode = response.StatusCode;
await context.Response.WriteAsJsonAsync(response); await context.Response.WriteAsJsonAsync(response);