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

时间:2016-03-20 12:28:03

标签: asp.net exception-handling owin asp.net-core-mvc middleware

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

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

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

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

提前致谢。

2 个答案:

答案 0 :(得分:1)

这是因为Exception页面需要​​有一个Exception对象才能使用。您的代码捕获异常然后被抑制。尝试重新抛出异常,如下所示:

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

答案 1 :(得分:1)

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

相关问题