gpt4 book ai didi

c# - ASP.NET 核心 UseExceptionHandler : Where's the exception?

转载 作者:行者123 更新时间:2023-12-03 07:51:41 26 4
gpt4 key购买 nike

在我的 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();
}

// ...
}
ErrorController 有一个这样的 Action :
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");
}

// ...
}
从我读过的内容来看,这应该给我另一个 Action 中发生的未处理异常。但事实并非如此。异常对象为空。我还尝试使用 IExceptionHandlerFeature 类型的其他功能但它是一样的。任何地方都不异常(exception)。
如何在错误处理程序中获取异常?
请注意,我正在使用重新执行功能,因为我讨厌在出现错误时将用户转发到不同的 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;
...
}

关于c# - ASP.NET 核心 UseExceptionHandler : Where's the exception?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65648570/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com