Exception handling 如何在ASP.NETMVC2中处理全局异常

Exception handling 如何在ASP.NETMVC2中处理全局异常,exception-handling,asp.net-mvc-2,Exception Handling,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 err

我的基本控制器具有以下覆盖:

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 = "myEmail@domain";
    // 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" />

我认为您需要在基本控制器上的覆盖方法中实现相同的逻辑。大概是这样的:

    protected override void OnException(ExceptionContext filterContext)
    {
        string AdminEmail = "myEmail@domain";
        // 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);
    }
你可以看一看。下面是关于ASP.NETMVC的。