WebAPI Global Exception Handling WebAPI Global Exception Handling asp.net asp.net

WebAPI Global Exception Handling


Actually when you add that filter to your HttpConfiguration it means that it will be executed for any action. That is, you don't need to add the whole attribute to your API controllers.

What can be skipping your filter? Other filter. The first filter to set the response wins and it can happen that the action itself gets never executed.

Anyway, maybe you need to switch to implement an IExceptionHandler and configure it as follows:

config.Services.Replace(typeof(IExceptionHandler), new MyExceptionHandler());

This approach is better because it's a true last-chance exception handler and it will be always called independently of the behavior of filters.


Like @ShekharPankaj had pointed out, not all exceptions are handled by the attribute (or the approach @Matías provided). My code was fine. I simple changed the exception to a ArgumentException and it gets handled.

See also this SO-thread: catch all unhandled exceptions in ASP.NET Web Api

To answer my own question, this isn't possible!

Handling all exceptions that cause internal server errors seems like a basic capability Web API should have, so I have put in a request with Microsoft for a Global error handler for Web API:

https://aspnetwebstack.codeplex.com/workitem/1001

If you agree, go to that link and vote for it!

In the meantime, the excellent article ASP.NET Web API Exception Handling shows a few different ways to catch a few different categories of error. It's more complicated than it should be, and it doesn't catch all interal server errors, but it's the best approach available today.

Update: Global error handling is now implemented and available in the nightly builds! It will be released in ASP.NET MVC v5.1. Here's how it will work: https://aspnetwebstack.codeplex.com/wikipage?title=Global%20Error%20Handling