ygo*_*goe 5 .net c# error-handling asp.net-core
在我的 ASP.NET Core 3.1 应用程序中,Startup 类中有这样的代码:
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseStatusCodePagesWithReExecute("/error/{0}");
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/error/500");
app.UseHsts();
}
// ...
}
Run Code Online (Sandbox Code Playgroud)
ErrorController 有一个像这样的操作:
public IActionResult Index(int id)
{
var context = HttpContext.Features.Get<IExceptionHandlerPathFeature>();
var exception = context?.Error;
if (exception != null)
{
logger.LogCritical(exception, $"Unhandled exception in request {HttpContext.TraceIdentifier}: {exception.GetRecursiveMessage()}");
}
else
{
logger.LogCritical(exception, $"Unhandled exception in request {HttpContext.TraceIdentifier}, no exception available");
}
// ...
}
Run Code Online (Sandbox Code Playgroud)
根据我所读到的内容,这应该给我在另一个操作中发生的未处理的异常。但事实并非如此。异常对象为空。我还尝试使用类型的其他功能IExceptionHandlerFeature,但它是一样的。任何地方都不例外。
如何在错误处理程序中获取异常?
请注意,我正在使用重新执行功能,因为我讨厌在出现错误时将用户转发到不同的 URL。这只会使事情变得更糟,因为重新加载页面以“重试”肯定永远不会解决任何问题(这是错误页面,毕竟,它只能显示错误)。
要获取异常对象,您可以使用IExceptionHandlerFeature
public IActionResult Error()
{
// Retrieve error information in case of internal errors
var error = HttpContext
.Features
.Get<IExceptionHandlerFeature>();
if (error == null)
...
// Use the information about the exception
var exception = error.Error;
...
}
Run Code Online (Sandbox Code Playgroud)