默认情况下,MVC 模板实现 HandleErrorAttribute att。我们可以在 Global.asax 中找到它(或者对于 MVC4 在 App_Start\FilterConfig.cs 中)
public static void RegisterGlobalFilters(GlobalFilterCollection filters) {
filters.Add(new HandleErrorAttribute());
}
如果在 web.config 中打开 CustomErrors,HandleErrorAttribute 会将用户重定向到默认错误页面。
要通过 HandleErrorAttribute 过滤器启用自定义错误处理,我们需要在应用程序的 Web.config 的 system.web 部分添加 customErrors 元素,如下所示:
<system.web>
<customErrors mode="On" defaultRedirect="Error.cshtml" />
</system.web>
语法:
<customErrors defaultRedirect="url" mode="On | Off | RemoteOnly">
</customErrors>
我们也可以有单独的视图,根据错误状态代码将用户重定向到特定的视图,如下所示:
<customErrors mode="On">
<error code="404" path="~/Views/Shared/NotFound.cshtml" />
<error code="500" path="~/Views/Shared/InternalServerError.cshtml" />
</customErrors>
现在让我们看看 HandleErrorAttribute 如何将用户重定向到默认的 Error.cshtml 视图。为了测试这一点,让我们从登录控制器的索引操作中抛出一个异常,如下所示:
public ActionResult Index() {
throw new ApplicationException("Error");
//return View();
}
我们将在默认 MVC 项目的 Shared 文件夹中看到 Errors.cshtml 的默认输出,这将返回正确的 500 状态消息,但我们的堆栈跟踪在哪里??
现在要捕获 Stack Trace,我们需要在 Error.cshtml 中进行一些修改,如下所示:
@model System.Web.Mvc.HandleErrorInfo
<hgroup>
<div class="container">
<h1 class="row btn-danger">Error.</h1>
@{
if (Request.IsLocal)
{
if (@Model != null && @Model.Exception != null)
{
<div class="well row">
<h4> Controller: @Model.ControllerName</h4>
<h4> Action: @Model.ActionName</h4>
<h4> Exception: @Model.Exception.Message</h4>
<h5>
Stack Trace: @Model.Exception.StackTrace
</h5>
</div>
}
else
{
<h4>Exception is Null</h4>
}
}
else
{
<div class="well row">
<h4>An unexpected error occurred on our website. The website administrator has been notified.</h4>
<br />
<h5>For any further help please visit <a href="http://abcd.com/"> here</a>. You can also email us anytime at support@abcd.com or call us at (xxx) xxx-xxxx.</h5>
</div>
}
}
</div>
</hgroup>
此更改可确保我们看到详细的堆栈跟踪。
试试这个方法看看。