I have a ASP WebAPI project. I'm trying to setup a global exception handler on my basecontroller. So I created an
public class MyExceptionFilterAttribute : ExceptionFilterAttribute
protected static readonly ILog log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
public override void OnException(HttpActionExecutedContext actionExecutedContext)
var exception = actionExecutedContext.Exception;
public static class WebApiConfig
public static void Register(HttpConfiguration config)
// Setup Filters
public string Hello(string name)
if (name.Equals("error", StringComparison.OrdinalIgnoreCase))
throw new HttpResponseException(HttpStatusCode.InternalServerError);
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:
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