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:
ExceptionHandlingAttribute
Application_Error
method in Global.asax.cs
AppDomain.CurrentDomain.UnhandledException
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:
IQueryable
returned by an action method fails to executeHttpConfiguration.MessageHandlers
)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?
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());