Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC4 Custom HandleErrorAttribute, method in global.asax not called

I can't get the Custom HandleErrorAttribute to be used in my MVC4 application.

Custom class which logs exception

  public class HandleAndLogErrorAttribute : HandleErrorAttribute
  {
    private static readonly Logger Logger = LogManager.GetCurrentClassLogger();

    public override void OnException(ExceptionContext filterContext)
    {
      var message = string.Format("Exception     : {0}\n" +
                                  "InnerException: {1}", 
                                  filterContext.Exception,
                                  filterContext.Exception.InnerException);
      Logger.Error(message);
      base.OnException(filterContext);
    }
  }

In Global.asax I've added a new static method:

  public class MvcApplication : System.Web.HttpApplication
  {
    protected void Application_Start()
    {
      AreaRegistration.RegisterAllAreas();

      WebApiConfig.Register(GlobalConfiguration.Configuration);
      FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
      RouteConfig.RegisterRoutes(RouteTable.Routes);
    }

    public static void RegisterGlobalFilters(GlobalFilterCollection filters)
    {
      filters.Add(new HandleAndLogErrorAttribute()); //Todo: log all errors
      throw new Exception("not called???");
    }

  }

When an exception is thrown, the error.chstml is loaded, but the OnException override in the custom HandlErrorAttribute is never called.

I suspect that the RegisterGlobalFilters method in Global.asax is not being called, and throwing an exception there (see code) confirms this. That exception is never thrown.

In the web.config file I've set customErrors On:

<customErrors mode="On">
</customErrors>

I've used the same approach in another solution, and I can't see why this HandleErrorAttribute extension is not working.

like image 564
Kman Avatar asked Jul 03 '13 14:07

Kman


1 Answers

You created RegisterGlobalFilters method inside your Global.asax, but since MVC 4 the global filters registration is specified in a seperate file in App_Start/FilterConfig.cs.

The line FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters) in your Global.asax is invoking the registration defined in the specified file.

Either add your custom filter registration in the specified file, or manually call your (local) RegisterGlobalFilters in Application_Start.

like image 190
haim770 Avatar answered Sep 19 '22 01:09

haim770