Add custom message support to exception handling middleware
This commit is contained in:
parent
84e6f7e2c9
commit
dffa410c71
1 changed files with 9 additions and 4 deletions
|
@ -30,10 +30,9 @@ public class ExceptionHandlingMiddleware
|
|||
|
||||
private async Task HandleExceptionAsync(HttpContext context, Exception exception)
|
||||
{
|
||||
_logger.LogError(exception, "An unexpected error occurred.");
|
||||
_logger.LogError(exception, "An error occurred.");
|
||||
|
||||
|
||||
var response = exception switch
|
||||
var defaultResponse = exception switch
|
||||
{
|
||||
BadRequestException _ => new ExceptionResponse(StatusCodes.Status400BadRequest, "Application exception occurred."),
|
||||
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.")
|
||||
};
|
||||
|
||||
var description = !string.IsNullOrWhiteSpace(exception.Message)
|
||||
? exception.Message
|
||||
: defaultResponse.Description;
|
||||
|
||||
var response = defaultResponse with { Description = description };
|
||||
|
||||
context.Response.ContentType = "application/json";
|
||||
context.Response.StatusCode = response.StatusCode;
|
||||
await context.Response.WriteAsJsonAsync(response);
|
||||
|
|
Loading…
Reference in a new issue