Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC 4 Global Exception Filter how to implement?

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();
    }
}
like image 342
user1166305 Avatar asked Dec 12 '12 02:12

user1166305


2 Answers

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!

like image 80
Thomas C. G. de Vilhena Avatar answered Sep 27 '22 16:09

Thomas C. G. de Vilhena


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());
like image 31
ScubaSteve Avatar answered Sep 27 '22 16:09

ScubaSteve