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

MVC6 - Handle unhandled exceptions and still have error page redirection

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

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

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

如何才能不打扰错误 page/module 但仍然在管道中捕获错误并将其记录下来?

提前致谢。

这是因为异常页面需要有一个 Exception 对象才能使用。您的代码捕获异常,然后将其抑制。尝试像这样重新抛出异常:

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

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