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 ErrorHandlerAttribute: System.Web.Mvc.FilterAttribute,
IExceptionFilter
{
public Task ExecuteExceptionFilterAsync(
HttpActionExecutedContext actionExecutedContext,
CancellationToken cancellationToken)
{
throw new NotImplementedException();
}
}
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<Logger>());
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!
The way I created an exception handler for MVC part of it, I created a class that implemented IExceptionFilter
public class MVCExceptionFilter : IExceptionFilter
{
public void OnException(ExceptionContext filterContext)
{
Trace.TraceError(filterContext.Exception.ToString());
}
}
You then register it in the Global.asax.cs
inside protected void Application_Start()
The method already contains the line
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
So, you will need to add this line ABOVE it
GlobalFilters.Filters.Add(new MVCExceptionFilter());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With