How to handle global exception in ASP.Net MVC 2

My base controller has this override:

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; } } 

I want to catch the exception and mail it. I can do the mail part, but not sure how to catch the exception? I am new to MVC. In Web Forms, I had it in 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" /> 
+4
source share
2 answers

I think you need to implement the same logic in your override method on the base controller. Something like that:

  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); } 
+1
source

You can take a look at ELMAH . Here is an example with ASP.NET MVC.

+2
source

Source: https://habr.com/ru/post/1308251/


All Articles