ASP.NET全局异常处理

  Web项目部署后,异常直接暴露给用户会产生很不好的体验。只是暴露在服务器端又无法实时记录异常原因以便加以重现并修复。所以配合Log4Net记录日志信息,同时全局异常处理来营造良好用户体验就比较重要了。

  在Web.config加以配置:

<httpModules>
      <add name="ErrorModule" type="ErrorModule"/>
</httpModules>

  早期开发时错误处理类放在App_Code里了,代码如下:

using System;
using System.Web;

public class ErrorModule : IHttpModule
{
    #region IHttpModule 成员

    void IHttpModule.Dispose() { }

    void IHttpModule.Init(HttpApplication context)
    {
        context.Error += new System.EventHandler(context_Error);
    }

    #endregion

    void context_Error(object sender, System.EventArgs e)
    {
        HttpContext context = HttpContext.Current;
        Exception ex = context.Server.GetLastError();
        String errorCode = Guid.NewGuid().ToString();
        String errorMsg = ex.InnerException == null ? ex.GetBaseException().Message : ex.InnerException.Message;
        //log4net.LogManager.GetLogger(GetType()).Error(BuildErrorString(errorCode, context));//Log4Netf辅助类
        context.Server.ClearError();
        ShowError(errorCode, errorMsg, context);
    }

    private String BuildErrorString(string errorCode, HttpContext context)
    {
        Exception ex = context.Server.GetLastError();
        System.Text.StringBuilder errorStr = new System.Text.StringBuilder();
        if (ex != null)
        {
            errorStr.Append("{ErrorCode:");
            errorStr.Append(errorCode);
            errorStr.Append(",ErrorPage:");
            errorStr.Append(context.Request.Url.ToString());
            errorStr.Append(",ErrorMsg:");
            errorStr.Append(ex.GetBaseException().Message);
            errorStr.Append(",StackTrace:");
            errorStr.Append(ex.StackTrace);
            if (ex.InnerException != null)
            {
                errorStr.Append(",InnerErrorMsg:");
                errorStr.Append(ex.InnerException.Message);
                errorStr.Append(",InnerStackTrace:");
                errorStr.Append(ex.InnerException.StackTrace);
            }
            errorStr.Append("}");
        }
        return errorStr.ToString();
    }

    private void ShowError(string errorCode, string errorMsg, HttpContext context)
    {
        HttpResponse response = context.Response;
        System.Text.StringBuilder errorPage = new System.Text.StringBuilder();
        errorPage.Append("<html><head><meta http-equiv='Content-Type' content='text/html; charset=utf-8'/></head><body>");
        errorPage.Append("<div style='margin:5px;border:1px solid #DDCCDD;padding:5px;'><p><strong>错误代码:</strong>");
        errorPage.Append(errorCode);
        errorPage.Append("</p><p><strong>错误消息:</strong>");
        errorPage.Append(errorMsg);
        errorPage.Append("</p><p><strong>系统异常请重试,若重复出现请联系系统管理员!</strong></p></div></body></html>");
        response.Write(errorPage.ToString());
        response.End();
        response.Clear();
    }
}

  捕获异常记录日志并呈现自定义页面,同时保留错误代码和主要信息便于反馈给系统管理员。

 

posted @ 2014-02-11 17:12  冰牙  阅读(535)  评论(0编辑  收藏  举报