catch all unhandled exceptions in ASP.NET Web Api

Joe Daley picture Joe Daley · Apr 16, 2013 · Viewed 59.9k times · Source

How do I catch all unhandled exceptions that occur in ASP.NET Web Api so that I can log them?

So far I have tried:

  • Create and register an ExceptionHandlingAttribute
  • Implement an Application_Error method in Global.asax.cs
  • Subscribe to AppDomain.CurrentDomain.UnhandledException
  • Subscribe to TaskScheduler.UnobservedTaskException

The ExceptionHandlingAttribute successfully handles exceptions that are thrown within controller action methods and action filters, but other exceptions are not handled, for example:

  • Exceptions thrown when an IQueryable returned by an action method fails to execute
  • Exceptions thrown by a message handler (i.e. HttpConfiguration.MessageHandlers)
  • Exceptions thrown when creating a controller instance

Basically, if an exception is going to cause a 500 Internal Server Error to be returned to the client, I want it logged. Implementing Application_Error did this job well in Web Forms and MVC - what can I use in Web Api?

Answer

decates picture decates · Jan 27, 2014

This is now possible with WebAPI 2.1 (see the What's New):

Create one or more implementations of IExceptionLogger. For example:

public class TraceExceptionLogger : ExceptionLogger
{
    public override void Log(ExceptionLoggerContext context)
    {
        Trace.TraceError(context.ExceptionContext.Exception.ToString());
    }
}

Then register with your application's HttpConfiguration, inside a config callback like so:

config.Services.Add(typeof(IExceptionLogger), new TraceExceptionLogger());

or directly:

GlobalConfiguration.Configuration.Services.Add(typeof(IExceptionLogger), new TraceExceptionLogger());