我一直在阅读有关ASP.NET Core中的错误处理的内容,我发现有这两种方法:
UseExceptionHandler("/error")
UseStatusCodePagesWithRedirects("/error/{0}");
我想知道这两者之间的区别是什么?它们都会重定向到错误页面,为什么要选择其中一个?我甚至看到有些人同时使用这两个方法。
我一直在阅读有关ASP.NET Core中的错误处理的内容,我发现有这两种方法:
UseExceptionHandler("/error")
UseStatusCodePagesWithRedirects("/error/{0}");
我想知道这两者之间的区别是什么?它们都会重定向到错误页面,为什么要选择其中一个?我甚至看到有些人同时使用这两个方法。
// …
await _next(context);
// …
// Do nothing if a response body has already been provided.
if (context.Response.HasStarted
|| context.Response.StatusCode < 400
|| context.Response.StatusCode >= 600
|| context.Response.ContentLength.HasValue
|| !string.IsNullOrEmpty(context.Response.ContentType))
{
return;
}
var statusCodeContext = new StatusCodeContext(context, _options, _next);
await _options.HandleAsync(statusCodeContext);
它通过调用_next
来执行管道,并在调用返回后(也就是所有后续中间件都执行完毕后),检查当前的响应:如果存在错误状态码或根本没有内容,则会执行指示HTTP状态码的状态码页。
另一方面,ExceptionHandler中间件则做了完全不同的事情:
try
{
await _next(context);
}
catch (Exception ex)
{
// …
try
{
// …
await _options.ExceptionHandler(context);
// …
return;
}
catch (Exception ex2)
{
// Suppress secondary exceptions, re-throw the original.
_logger.ErrorHandlerException(ex2);
}
throw; // Re-throw the original if we couldn't handle it
}