2014-10-06 66 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