This commit is contained in:
2025-05-11 17:40:51 +08:00
parent 992721b280
commit e2f75fb4dd

View File

@@ -19,8 +19,12 @@
private async Task HandleExceptionAsync(HttpContext context, Exception ex) private async Task HandleExceptionAsync(HttpContext context, Exception ex)
{ {
context.Response.ContentType = "application/problem+json"; if (!context.Response.HasStarted)
context.Response.StatusCode = StatusCodes.Status500InternalServerError; {
context.Response.ContentType = "application/problem+json";
context.Response.StatusCode = StatusCodes.Status500InternalServerError;
}
var title = ""; var title = "";
var message = ""; var message = "";
var exType = ex.GetType(); var exType = ex.GetType();
@@ -50,22 +54,25 @@
_logger.LogError(ex, "Exception"); _logger.LogError(ex, "Exception");
} }
var acceptHeader = context.Request.Headers["Accept"].FirstOrDefault(); if (!context.Response.HasStarted)
var isAjaxRequest = acceptHeader?.Contains("application/json") == true;
if (isAjaxRequest)
{ {
var problem = new ProblemDetails var acceptHeader = context.Request.Headers["Accept"].FirstOrDefault();
var isAjaxRequest = acceptHeader?.Contains("application/json") == true;
if (isAjaxRequest)
{ {
Status = StatusCodes.Status500InternalServerError, var problem = new ProblemDetails
Title = title, {
Type = "https://tools.ietf.org/html/rfc7231#section-6.5.1", Status = StatusCodes.Status500InternalServerError,
Detail = message Title = title,
}; Type = "https://tools.ietf.org/html/rfc7231#section-6.5.1",
await context.Response.WriteAsJsonAsync(problem); Detail = message
} };
else await context.Response.WriteAsJsonAsync(problem);
{ }
await context.Response.WriteAsync(message); else
{
await context.Response.WriteAsync(message);
}
} }
} }