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)
|
private static async Task HandleExceptionAsync(HttpContext context, Exception exception, ILogger logger)
|
||||||
{
|
{
|
||||||
context.Response.ContentType = "application/json";
|
context.Response.ContentType = "application/json";
|
||||||
var response = context.Response;
|
|
||||||
|
|
||||||
string message;
|
string message;
|
||||||
int statusCode;
|
|
||||||
|
|
||||||
switch (exception)
|
switch (exception)
|
||||||
{
|
{
|
||||||
case BadRequestException badRequestEx:
|
case BadRequestException badRequestEx:
|
||||||
statusCode = (int)HttpStatusCode.BadRequest;
|
context.Response.StatusCode = (int)HttpStatusCode.BadRequest;
|
||||||
message = badRequestEx.Message;
|
message = badRequestEx.Message;
|
||||||
break;
|
break;
|
||||||
|
|
||||||
case NotFoundException notFoundEx:
|
case NotFoundException notFoundEx:
|
||||||
statusCode = (int)HttpStatusCode.NotFound;
|
context.Response.StatusCode = (int)HttpStatusCode.NotFound;
|
||||||
message = notFoundEx.Message;
|
message = notFoundEx.Message;
|
||||||
break;
|
break;
|
||||||
|
|
||||||
default:
|
default:
|
||||||
logger.LogError(exception, "Unhandled exception occurred.");
|
logger.LogError(exception, "Unhandled exception occurred.");
|
||||||
statusCode = (int)HttpStatusCode.InternalServerError;
|
context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
|
||||||
message = "An unexpected error occurred.";
|
message = "An unexpected error occurred.";
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
|
||||||
response.StatusCode = statusCode;
|
await context.Response.WriteAsync(JsonSerializer.Serialize(new
|
||||||
|
|
||||||
var result = JsonSerializer.Serialize(new
|
|
||||||
{
|
{
|
||||||
error = message
|
message
|
||||||
});
|
}));
|
||||||
|
|
||||||
await context.Response.WriteAsync(result);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Loading…
x
Reference in New Issue
Block a user