How do I implement a global exception handler in MVC4 as it seems to be different from MVC3.
Not sure how to implement the following:
public class E
Unfortunately the link provided in Eric Leschinski's commet only shows how to implement the System.Web.Mvc.IExceptionFilter interface, and not the System.Web.Http.Filters.IExceptionFilter interface. The first is used in regular MVC controllers, while the second targets ApiCotrollers.
Here is a simple class example I came up with for logging unhandled exceptions thrown in my ApiControllers:
public class ExceptionLoggerFilter: IExceptionFilter
{
public ExceptionLoggerFilter(Logger logger)
{
this.logger = logger;
}
public bool AllowMultiple { get { return true; } }
public Task ExecuteExceptionFilterAsync(
HttpActionExecutedContext actionExecutedContext,
CancellationToken cancellationToken)
{
return Task.Factory.StartNew(() =>
{
logger.Error("web service error", actionExecutedContext.Exception);
}, cancellationToken);
}
private Logger logger;
}
And all you have to do to enable this filter is register it in yours Global.asax Application_Start method:
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
// allocate filter and add it to global configuration
var exceptionLogger = new ExceptionLoggerFilter(Container.Get());
GlobalConfiguration.Configuration.Filters.Add(exceptionLogger);
WebApiConfig.Register(GlobalConfiguration.Configuration);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
}
I hope this helps other googlers out there!