ASP.NETグローバル例外処理
6884 ワード
Webプロジェクトの導入後、異常が直接ユーザーに露出すると、悪い体験になります.サーバ側に露出しているだけで、例外の原因をリアルタイムで記録して再現し、修復することはできません.そのため、Log 4 Netのログ情報の記録に合わせて、グローバルな異常処理を行い、ユーザー体験を良好にすることが重要です.
Web.configを構成するには、次の手順に従います.
初期開発時にエラー処理クラスがAppに置かれたコードは次のとおりです.
異常レコード・ログを取得し、カスタム・ページを表示します.エラー・コードと主な情報を保持して、システム管理者にフィードバックしやすくします.
Web.configを構成するには、次の手順に従います.
<httpModules>
<add name="ErrorModule" type="ErrorModule"/>
</httpModules>
初期開発時にエラー処理クラスがAppに置かれたコードは次のとおりです.
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();
}
}
異常レコード・ログを取得し、カスタム・ページを表示します.エラー・コードと主な情報を保持して、システム管理者にフィードバックしやすくします.