2012-11-11 30 views
3

我想弄清楚一種方法來捕獲網站上的所有異常並存儲它們,以及問題是我不想去嘗試抓住一切。捕捉網站上的所有異常最好的方法

我已經想出了自定義錯誤頁面的解決方案,我正在這樣做,但是我想以管理員身份知道用戶何時遇到錯誤以及出現了什麼錯誤。我知道必須有一種方法來全局獲取所有異常並將其存儲。

我一直在尋找一種解決方案,或者至少在某些方面指向正確的方式幾天,但我所發現的一切都是笨拙的做法。

所以我的問題是。有沒有一站式商店這種事情?我是否可以捕獲異常並在一個地方執行存儲過程,而無需在解決方案中爲每個類添加內容?在那種情況下,我在哪裏運行我的存儲過程?

回答

2

添加Global.asax文件到您的asp.net項目和處理應用程序錯誤:

void Application_Error(object sender, EventArgs e) 
    { 
     Exception ex = Server.GetLastError(); 
     string errorMessage = "Application Exception: " + ex.Message; 
     if (ex.InnerException != null) 
     { 
      errorMessage += Environment.NewLine + "Inner Exception: " + ex.InnerException.Message; 
     } 
     if (Context != null && Context.Request != null) 
     { 
      errorMessage += Environment.NewLine + "Absolute Url: " + Context.Request.Url.AbsolutePath; 
     } 
     Services.LoggerManager.Log(
      Services.LoggerManager.eLogContext.Application, 
      Services.LoggerManager.eLogType.Error, 
      Context, errorMessage); 
    } 

這裏是LoggerManager部分:

public static class LoggerManager 
{ 

    public enum eLogType 
    { 
     Information = 0, 
     Warning = 1, 
     Error = 2 
    } 

    public enum eLogContext 
    { 
     Application = 0, 
     Session = 1 
    } 

    /// <summary> 
    /// Method for logging custom message 
    /// </summary> 
    /// <param name="logContext"></param> 
    /// <param name="logType"></param> 
    /// <param name="context"></param> 
    /// <param name="message"></param> 
    public static void Log(eLogContext logContext, eLogType logType, HttpContext context, string message) 
    { 
     switch (logContext) 
     { 
      case eLogContext.Application: 
       //TODO: log application type event... 
       break; 
      case eLogContext.Session: 
       //TODO: log session type event... 
       break; 
      default: 
       throw new NotImplementedException("eLogContext '" + logContext.ToString() + "' is not implemented!"); 
     } 
    } 

} 
+0

如果我想一個警告可能我只是添加Application_Warning (對象發件人,EventArgs e)到global.asax? –

+0

不是。 Global.asax不支持此事件。但是,您可以處理特定的asp.net頁面內的異常,然後調用LoggerManager.Log( Services.LoggerManager.eLogContext.Application, Services.LoggerManager.eLogType.Warning, Context,warningMessage); –

+0

我想要說明一點,我必須在每次使用**的地方使用throw代碼**嘗試**和** catch ** –

1

我建議在ELMAH http://code.google.com/p/elmah/考慮看看

這是非常受歡迎的,並提供從nuget也。它旨在很容易地捕捉和管理所有錯誤。如果你不想自己管理錯誤,我強烈推薦它。