在 ASP.NET 中更优雅地处理错误的一种方法是使用 CustomError 页面的组合,这样最终用户就不会看到臭名昭著的“黄屏死机”以及一些记录错误的技术错误详情,以便稍后解决具体问题。
向用户展示自定义错误页面
根据我的经验,在 ASP.NET 中处理此问题的最佳方法是使用 web.config 中的 customErrors 节点,如下所示:
<customErrors mode="RemoteOnly" defaultRedirect="~/Error/Default.aspx">
<error statusCode="401" redirect="~/Error/Default/Unauthorized.aspx" />
<error statusCode="403" redirect="~/Error/Default/PageNotFound.aspx" />
<error statusCode="404" redirect="~/Error/Default/PageNotFound.aspx" />
<error statusCode="408" redirect="~/Error/Default/RequestTimeout.aspx" />
<error statusCode="505" redirect="~/Error/Default/NotSupported.aspx" />
</customErrors>
此节点位于 /configuration/system.web/customErrors 中。这是link with more information written by ASP.NET guru Scott Mitchell。 customError 节点上的“defaultRedirect”属性告诉 ASP.NET 如果抛出未处理的异常,则显示哪个页面。这是一个自定义错误页面的示例,它似乎与我们本地 Intranet 上的用户很好地配合,虽然它是为 MVC 编写的,但应该很容易将其转换为 WebForms:
<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Master/Site.Master" Inherits="System.Web.Mvc.ViewPage<dynamic>" %>
<asp:Content ID="Content1"
ContentPlaceHolderID="TitleContent"
runat="server">
Unknown Error - Organization or Website Name
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<div id="error">
<h3 id="status">Something Unexpected Happened</h3>
<p id="details" style="margin-top: 15px">
Your request could not be fully processed most likely because of a computer programming
or data corruption problem. Errors like these are logged with the date, time, a
detailed error message (sometimes called a stack trace), the errant URL, and normally
the user making the request along with some additional information.
<br />
<br />
The web team tries to check and troubleshoot these logs daily depending on our
general work load. If you're having a problem that can be repeated, please send
me a message and include the current time (<%= DateTime.Now.ToString() %>) along
with a brief description of what you were trying to do. Feedback of this nature is
appreciated and absolutely essential.
</p>
<p>
--
<br />
Organization Web Team or Appropriate Help Desk<br />
Phone: (555) 555-5555<br />
Email: <a href="mailto:web.team@your.organization.org?subject=Application%20Error">web.team@your.organization.org</a>
</p>
</div>
</asp:Content>
记录未处理的异常
我最喜欢在 ASP.NET 中记录未处理异常的方法之一是使用“健康监控系统”。这里又是another article by Scott Mitchell which describes ASP.NET's Health Monitoring System。 Health Monitoring 是在 2.0 框架中引入的,因此它应该对您的应用程序有用。简而言之,健康监控可用于将未处理的异常记录到数据库、事件查看器中,并且可以直接通过电子邮件发送它们。它也可以通过一些工作进行扩展,也可以用于记录处理的异常。正如文章指出的,健康监控是通过节点 /configuration/system.web/healthMonitoring 的 web.config 配置的。