MVC6 - 处理未经处理的异常,但仍有错误页面重定向



在我的MVC6应用程序中,我创建了一个中间件来处理使用调用任务的全局未处理异常,如下所示:

try
{
    await _next.Invoke(context);
}
catch (System.Exception e)
{
    ... Log the exception here...
}

我面临的问题是,如果我在添加 UseDeveloperExceptionPage/UseExceptionHandle 之前在配置部分添加它,那么中间件中的 catch 块就不会被命中。当我在UseDeveloperExceptionPage/UseExceptionHandle之后添加它时,错误页面或模块没有得到处理。

我怎样才能不打扰错误页面/模块,但仍然捕获管道中的错误并记录它?

提前谢谢。

这是因为"异常"页需要有一个Exception对象才能使用。您的代码捕获异常,然后禁止显示该异常。尝试像这样重新引发异常:

try
{
    await _next.Invoke(context);
}
catch (System.Exception e)
{
    //Log the exception here...
    throw;
}

只需重新抛出错误就会导致堆栈跟踪显示源自中间件的错误。您需要像这样抛出错误:ExceptionDispatchInfo.Capture(e).Throw();

最新更新