Thijs Thijs - 3 months ago 39
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

ExceptionFilterAttribute
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;
log.Fatal(exception);

base.OnException(actionExecutedContext);
}
}


Then I also registered it in
/App_Start/WebApiConfig.cs


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:

[HttpGet]
public string Hello(string name)
{
if (name.Equals("error", StringComparison.OrdinalIgnoreCase))
{
throw new HttpResponseException(HttpStatusCode.InternalServerError);
}
else
{
return name;
}
}

Answer

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