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)
|
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."),
|
||||||
|
@ -44,7 +43,13 @@ public class ExceptionHandlingMiddleware
|
||||||
UnavailableForLagalReasonsException _ => new ExceptionResponse(StatusCodes.Status451UnavailableForLegalReasons, "Unavailable for legal reasons."),
|
UnavailableForLagalReasonsException _ => new ExceptionResponse(StatusCodes.Status451UnavailableForLegalReasons, "Unavailable for legal reasons."),
|
||||||
_ => 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);
|
||||||
|
|
Loading…
Reference in a new issue