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 inGlobal.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?