2010-04-28 67 views
4

我的基本控制器具有此覆盖:如何处理全局异常在ASP.Net MVC 2

protected override void OnException(ExceptionContext filterContext) 
{ 
    // http://forums.asp.net/t/1318736.aspx 
    if (filterContext == null) 
    { 
     throw new ArgumentNullException("filterContext"); 
    } 
    // If custom errors are disabled, we need to let the normal ASP.NET exception handler 
    // execute so that the user can see useful debugging information. 
    if (filterContext.ExceptionHandled || !filterContext.HttpContext.IsCustomErrorEnabled) 
    { 
     return; 
    } 

    Exception exception = filterContext.Exception; 

    // If this is not an HTTP 500 (for example, if somebody throws an HTTP 404 from an action method), 
    // ignore it. 
    if (new HttpException(null, exception).GetHttpCode() != 500) 
    { 
     return; 
    } 
} 

我想捕获异常并寄出。我可以做邮件的一部分,但不知道如何收集异常?我是MVC的新手。在Web窗体我在Global.asax中

void Application_Error(object sender, EventArgs e) 
{ 
    string AdminEmail = "[email protected]"; 
    // Code that runs when an unhandled error occurs 
    Exception objErr = Server.GetLastError().GetBaseException(); 
    string err = "Error Caught in Application_Error event\n" + 
      "Error in: " + Request.Url.ToString() + 
      "\n Error Message:" + objErr.Message.ToString() + 
      "\n Stack Trace:" + objErr.StackTrace.ToString(); 
    // Below uses: using System.Diagnostics; 
    //EventLog.WriteEntry("Sample_WebApp", err, EventLogEntryType.Error); 
    //Server.ClearError(); // Clear error prohibits it from showing on page 
    //additional actions... 

    MyApp.Utility.Email.Send(AdminEmail, CommonLibrary.FromEmail, "Asp.net Application Error", err); 
} 

的Web.config

<customErrors mode="On" /> 

回答

1

我认为你需要实现基本控制器上的覆盖方法相同的逻辑了这一点。类似这样的:

protected override void OnException(ExceptionContext filterContext) 
    { 
     string AdminEmail = "[email protected]"; 
     // Code that runs when an unhandled error occurs 
     Exception objErr = filterContext.Exception; 
     string err = "Error Caught in Application_Error event\n" + 
       "Error in: " + Request.Url.ToString() + 
       "\n Error Message:" + objErr.Message.ToString() + 
       "\n Stack Trace:" + objErr.StackTrace.ToString(); 
     // Below uses: using System.Diagnostics; 
     //EventLog.WriteEntry("Sample_WebApp", err, EventLogEntryType.Error); 
     //Server.ClearError(); // Clear error prohibits it from showing on page 
     //additional actions... 

     MyApp.Utility.Email.Send(AdminEmail, CommonLibrary.FromEmail, "Asp.net Application Error", err); 
     base.OnException(filterContext); 
    } 
2

你可以看看ELMAH。这里的an example与ASP.NET MVC。

+0

+1对于ELMAH ...如果你不需要,不要重新发明轮子。 – Webjedi 2010-04-28 20:59:18