2014-10-06 86 views
2

所以我有一個全局錯誤處理程序,每當我的應用程序出現錯誤時都會發送一封電子郵件。這很好,但是,有一些錯誤(即可怕的「對象引用未設置爲對象實例」錯誤),這些錯誤非常難以追蹤。我有一個整潔的函數,可以將序列化模型轉換爲字符串,因此我可以實際看到有問題的代碼行處理的數據,但是我想知道是否有方法可以在應用程序中捕獲模型級錯誤處理程序?我得到了我需要的所有東西,例如url,堆棧跟蹤等,只是對當前正在處理的數據沒有可見性。這是我目前在我的Application_Error:在Application_Error中獲取當前模型

protected void Application_Error(object sender, EventArgs e) 
    { 
     Exception exception = Server.GetLastError(); 
     HttpContext con = HttpContext.Current; 
     string serverUrl = ""; 
     if (con.Request != null) 
     { 
      serverUrl = con.Request.Url.ToString(); 
     } 
     var user = ""; 

     if (GlobalSiteData.CurrentUser != null) user = GlobalSiteData.CurrentUser.Username; 
     var ip = (Request.UserHostAddress == null ? "" : Request.UserHostAddress.ToString()); 
     try { 
      Mailers.UserMailer mailer = new Mailers.UserMailer(); 
      ErrorLog elog = new ErrorLog 
      { 
       ErrorDate = DateTime.Now, 
       InnerException = (exception.InnerException == null ? "" : exception.InnerException.Message), 
       Message = exception.Message, 
       UserName = user, 
       Source = exception.TargetSite.Name, 
       SourceUrl = serverUrl, 
       StackTrace = exception.StackTrace, 
       IPAddr = ip 
      }; 
      mailer.LogEntry(elog).Send(); 
      ErrorHelpers.LogErrorToFile(elog); 
     } 
     catch (Exception ex) 
     { 
      string err = ex.Message; 
     } 
    } 

回答

3

如果這是一個MVC應用程序,那麼我會建議您使用錯誤處理程序。這樣你就可以訪問filterContext,它應該有你需要的一切。

將以下行註冊到global.asax或AppStart文件夾中的FilterConfig.cs中。

filters.Add(new CustomHandleErrorAttribute());

創建以下類並添加所需的日誌記錄。這應該記錄在MVC框架內發生的所有異常。除了MVC框架外,還有一些條件無法解決,但大多數情況下這應該是第一道防線。我將鏈接使用MVC控制器上提供的OnException方法的另一個選項。

public class CustomHandleErrorAttribute: HandleErrorAttribute { 

     public override void OnException(ExceptionContext filterContext) 
     { 
      if (filterContext.Exception != null) 
      { 
      // do something 
      } 

      base.OnException(filterContext); 
     } 
    } 

下面是另一種僅適用於MVC的錯誤處理方法。

http://blog.dantup.com/2009/04/aspnet-mvc-handleerror-attribute-custom.html