异常处理
Developer 环境的异常页面
ASP.NET Core App 会可以在开发阶段用UseDeveloperExceptionPage启用 Developer 异常页面:
app.UseDeveloperExceptionPage();
当遇到Unhandled 异常信息时,可以输出异常信息页面:
异常信息包括:
- Stack trace
- Query string parameters, if any
- Cookies, if any
- Headers
Production 环境的异常页面
在测试和上线阶段,可以用UseExceptionHandler 捕获异常:
var app = builder.Build();
if (!app.Environment.IsDevelopment()) //仅在开发环境输出这些详细信息
{
app.UseExceptionHandler("/Error");
app.UseHsts();
}
UseExceptionHandler 会捕获和记录异常信息,并重新执行客户端的request,所以要注意重新执行request的重入逻辑。
记录异常
可以使用 IExceptionHandlerPathFeature 获取异常的详细信息,然后写入log:
public void OnGet()
{
RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier;
var exceptionHandlerPathFeature =
HttpContext.Features.Get<IExceptionHandlerPathFeature>();
if (exceptionHandlerPathFeature?.Error is FileNotFoundException)
{
ExceptionMessage = "The file was not found.";
}
if (exceptionHandlerPathFeature?.Path == "/")
{
ExceptionMessage ??= string.Empty;
ExceptionMessage += " Page: Home.";
}
}
返回错误代码 UseStatusCodePages
当找不到endpoint时,会返回404。可以返回400-599的code。
var app = builder.Build();
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Error");
app.UseHsts();
}
app.UseStatusCodePages();
UseStatusCodePages 一般不用于Production环境,因为返回的信息对于用户来说没有意义。