44

For a project I am working on, one of the things we're implementing is something that we have code for in some of my teams older ASP.NET and MVC projects - an Application_Error exception catcher that dispatches an email to the development team with the exception experience and most relevant details.

Here's how it looks:

Global.asax:

protected void Application_Error(object sender, EventArgs e)
{
    Exception ex = Server.GetLastError();
    string path = "N/A";
    if (sender is HttpApplication)
        path = ((HttpApplication) sender).Request.Url.PathAndQuery;

    string args = string.Format("<b>Path:</b> {0}", path);

    // Custom code that generates an HTML-formatted exception dump
    string message = Email.GenerateExceptionMessage(ex, args);

    // Custom code that sends an email to the dev team.
    Email.SendUnexpectedErrorMessage("Some App", message);
}

One "minor" problem, though - when I intentionally have a part of the code throw an exception in order to test this mechanism...

public static void GetMuffinsByTopping(string topping)
{
    throw new Exception("Test Exception!", new Exception("Test Inner Exception!!!"));

    // Actual repository code is unreachable while this test code is there
}

The front-end JavaScript is immediately intercepting an HTTP 500 request, but the global.asax.cs code noted above is not being reached (I set a breakpoint on the first executing line of the method.)

Question: In what way can I get the "old" Application_Error handler to dispatch error emails, so that our team's developers can more easily debug our application?

4
  • 1
    You could abstract your error handling logic into a separate method that Application_Error calls, wrap the Web API method body in a try/catch, then manually pass the error logic to the abstracted method from Web API errors. Not the cleanest way I'm sure, but it should be straightforward to implement and "just work". For a cleaner method you might look at Exception Handling in ASP.NET Web API.
    – mason
    Feb 27, 2015 at 15:36
  • I agree that it's a good "just get it working" suggestion. The reason I ask this is that having a try/catch in every API method is actually what I'm trying to get away from, per my tech lead's guidance. If all else fails, our team can use this as a fallback, though. It will just be a very obnoxious pattern. Feb 27, 2015 at 15:39
  • 1
    I edited my last comment. Look at the link I provided, and have a look at exception filters. That looks like a decent way to avoid having try/catch in all your Web API method bodies.
    – mason
    Feb 27, 2015 at 15:41
  • That wound up working out for me. Would you mind making an answer of your comment that using an Exception Filter is a better way to do this? Feb 27, 2015 at 16:32

2 Answers 2

83

Abstract out your error handling logic from Application_Error into its own function. Create a Web API exception filter.

//register your filter with Web API pipeline
//this belongs in the Application_Start event in Global Application Handler class (global.asax)
//or some other location that runs on startup
GlobalConfiguration.Configuration.Filters.Add(new LogExceptionFilterAttribute());

//Create filter
public class LogExceptionFilterAttribute : ExceptionFilterAttribute 
{
    public override void OnException(HttpActionExecutedContext context)
    {
        ErrorLogService.LogError(context.Exception);
    }
}

//in global.asax or global.asax.cs
protected void Application_Error(object sender, EventArgs e)
{
    Exception ex = Server.GetLastError();
    ErrorLogService.LogError(ex);
} 

//common service to be used for logging errors
public static class ErrorLogService
{
    public static void LogError(Exception ex)
    {
        //Email developers, call fire department, log to database etc.
    }
}

Errors from Web API do not trigger the Application_Error event. But we can create an exception filter and register it to handle the errors. Also see Global Error Handling in ASP.NET Web API 2.

9
  • Why? I did not understand it. It's the best pratice? Jan 3, 2017 at 13:12
  • 7
    @LeandroDeMelloFagundes The Application_Error event doesn't get fired when Web API has an exception. You probably already have logging in Application_Error to handle ASP.NET exceptions. So putting that logic in a common service that can be used from either Application_Error or an exception filter applied to your Web API action methods follows the DRY principle. No duplicated logic.
    – mason
    Jan 3, 2017 at 13:14
  • 1
    Thanks @mason, reading the link on your answer from the asp.net site helped a lot to understand what happens too. Great aswer Jan 3, 2017 at 13:51
  • 1
    Where are you supposed to put the line : GlobalConfiguration.Configuration.Filters.Add(new LogExceptionFilterAttribute()); Is it in global.asax Application_Start() or Application_Error()?
    – Paul
    May 24, 2017 at 14:00
  • @Paul It should be in Application_Start, because you're registering the filter so that it knows how to handle the error when it happens. You'd always register any filter at application start.
    – mason
    May 24, 2017 at 14:03
-2

In my case, i prefer not use Web.config. Then i created code above in Global.asax file:

protected void Application_Error(object sender, EventArgs e)
    {
        Exception ex = Server.GetLastError();

        //Not Found (When user digit unexisting url)
        if(ex is HttpException && ((HttpException)ex).GetHttpCode() == 404)
        {
            HttpContextWrapper contextWrapper = new HttpContextWrapper(this.Context);

            RouteData routeData = new RouteData();
            routeData.Values.Add("controller", "Error");
            routeData.Values.Add("action", "NotFound");

            IController controller = new ErrorController();
            RequestContext requestContext = new RequestContext(contextWrapper, routeData);
            controller.Execute(requestContext);
            Response.End();
        }
        else //Unhandled Errors from aplication
        {
            ErrorLogService.LogError(ex);
            HttpContextWrapper contextWrapper = new HttpContextWrapper(this.Context);

            RouteData routeData = new RouteData();
            routeData.Values.Add("controller", "Error");
            routeData.Values.Add("action", "Index");

            IController controller = new ErrorController();
            RequestContext requestContext = new RequestContext(contextWrapper, routeData);
            controller.Execute(requestContext);
            Response.End();
        }
    }

And thtat is my ErrorController.cs

public class ErrorController : Controller
{
    // GET: Error
    public ViewResult Index()
    {
        Response.StatusCode = 500;
        Exception ex = Server.GetLastError();
        return View("~/Views/Shared/SAAS/Error.cshtml", ex);
    }

    public ViewResult NotFound()
    {
        Response.StatusCode = 404;
        return View("~/Views/Shared/SAAS/NotFound.cshtml");
    }
}

And that is my ErrorLogService.cs copyed from @mason class

//common service to be used for logging errors
public static class ErrorLogService
{
    public static void LogError(Exception ex)
    {
        //Do what you want here, save log in database, send email to police station
    }
}
1
  • 1
    This doesn't answer the OP's question, nor does his code reference Web.config.
    – facechomp
    Jun 19, 2020 at 5:57

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.