处理任何 Web 应用程序中的异常,都可以使用 simple 来捕获和管理运行时发生的异常。ExceptionHandlerMiddleware
上述中间件已通过自定义选项进一步启用,以允许开发人员根据异常类型处理 HTTP 状态代码和返回。
长期以来,它一直是 ASP.Net Core 的一部分,用于在运行时处理和处理异常。如果出现未处理的异常,将返回上述功能。ExceptionHandlerMiddleware500 Internal Server Error
尽管中间件提供了一个集中式管道来拦截异常并确保响应模型一致,但在发生异常时,必须显式处理基于状态代码的响应。
本文演示了 .Net 9 中提供的 option 的新功能,它将改进异常/错误处理。StatusCodeSelector
.Net 中可用的最新更新提供了基于状态代码处理响应的功能。StatusCodeSelector
使用选项自定义 return by based on exception type 的状态代码:StatusCodeSelectorExceptionHandlerMiddleware
// Configure ExceptionHandlerMiddleware
app.UseExceptionHandler(new ExceptionHandlerOptions
{
ExceptionHandler = async context =>
{
var exception = context.Features.Get\<IExceptionHandlerFeature>().Error;
var statusCode = context.Response.StatusCode;
// Customize the response based on the exception
if (exception is TimeoutException)
{
statusCode = StatusCodes.Status503ServiceUnavailable;
}
else
{
statusCode = StatusCodes.Status500InternalServerError;
}
context.Response.ContentType = "application/problem+json";
context.Response.StatusCode = statusCode;
var problemDetails = new
{
Status = statusCode,
Title = "An error occurred while processing your request.",
Detail = exception.Message
};
await context.Response.WriteAsJsonAsync(problemDetails);
},
StatusCodeSelector = ex => ex is TimeoutException
? StatusCodes.Status503ServiceUnavailable
: StatusCodes.Status500InternalServerError,
});
app.UseExceptionHandler(new ExceptionHandlerOptions
{
StatusCodeSelector = ex => ex is TimeoutException
? StatusCodes.Status503ServiceUnavailable
: StatusCodes.Status500InternalServerError,
});
上述增强提供了增强的调试功能,并改进了代码处理语义,因为不同的状态码表示不同的含义。开发人员可以根据 API 返回的状态码解决问题。
中的新选项允许开发人员自定义为响应不同的异常而返回的状态代码,并增强了更准确、更有意义地传达错误条件的能力。