Refactor exception handling in middleware
Updated `HandleExceptionAsync` to set response status directly for each exception type and streamlined JSON serialization of error messages.
This commit is contained in:
parent
4ee5250b01
commit
972b258706
@ -54,37 +54,31 @@ public class ExceptionHandlingMiddleware
|
||||
private static async Task HandleExceptionAsync(HttpContext context, Exception exception, ILogger logger)
|
||||
{
|
||||
context.Response.ContentType = "application/json";
|
||||
var response = context.Response;
|
||||
|
||||
string message;
|
||||
int statusCode;
|
||||
|
||||
switch (exception)
|
||||
{
|
||||
case BadRequestException badRequestEx:
|
||||
statusCode = (int)HttpStatusCode.BadRequest;
|
||||
context.Response.StatusCode = (int)HttpStatusCode.BadRequest;
|
||||
message = badRequestEx.Message;
|
||||
break;
|
||||
|
||||
case NotFoundException notFoundEx:
|
||||
statusCode = (int)HttpStatusCode.NotFound;
|
||||
context.Response.StatusCode = (int)HttpStatusCode.NotFound;
|
||||
message = notFoundEx.Message;
|
||||
break;
|
||||
|
||||
default:
|
||||
logger.LogError(exception, "Unhandled exception occurred.");
|
||||
statusCode = (int)HttpStatusCode.InternalServerError;
|
||||
context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
|
||||
message = "An unexpected error occurred.";
|
||||
break;
|
||||
}
|
||||
|
||||
response.StatusCode = statusCode;
|
||||
|
||||
var result = JsonSerializer.Serialize(new
|
||||
await context.Response.WriteAsync(JsonSerializer.Serialize(new
|
||||
{
|
||||
error = message
|
||||
});
|
||||
|
||||
await context.Response.WriteAsync(result);
|
||||
message
|
||||
}));
|
||||
}
|
||||
}
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user