Thijs Thijs - 5 months ago 82
ASP.NET (C#) Question

WebAPI Global Exception Handling

I have a ASP WebAPI project. I'm trying to setup a global exception handler on my basecontroller. So I created an

like so.

using System.Web.Http.Filters;

public class MyExceptionFilterAttribute : ExceptionFilterAttribute
protected static readonly ILog log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);

public override void OnException(HttpActionExecutedContext actionExecutedContext)
var exception = actionExecutedContext.Exception;


Then I also registered it in

public static class WebApiConfig
public static void Register(HttpConfiguration config)
// ...

// Setup Filters
config.Filters.Add(new MyExceptionFilterAttribute());

When I add the attributes to my controller (or base-controller), nothing gets logged. What am I doing wrong?

Edit: My controller throwing the exception:

public string Hello(string name)
if (name.Equals("error", StringComparison.OrdinalIgnoreCase))
throw new HttpResponseException(HttpStatusCode.InternalServerError);
return name;


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: