Search code examples
c#asp.net-mvcasp.net-mvc-4exceptionasp.net-apicontroller

ASP NET MVC OnException not being called ApiController


I am trying to intercept all exceptions, but the code is never run. I have tried putting this to GlobalFilters, and also putting it directly on my method.

My Attributes:

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = false)]
public class HandleExceptionAttribute : HandleErrorAttribute 
{
    private ILog log = LogManager.GetLogger(typeof(HandleExceptionAttribute));

    public override void OnException(ExceptionContext filterContext) 
    {
        log.Info("inside on exception"); // this never appears
    }
}

My class:

public class Tester 
{
    [HandleException]
    public void Except() 
    {
        var asd = 0;
        var qwe = 1 / asd;              
    }
}

Dividing by zero give me an exception, my debugger catches it, I continue, but nothing is written into log file.

The logger works. Other logs appear in file. Even if I disable debugging, it doesn't read the log file, so it's not debuggers fault.

Running this on IIS Express. Windows 7.

EDIT:

Moved the thing to controller. Still not working

public class UserController : ApiController 
{
    private ILog log = LogManager.GetLogger(typeof(UserController));

    [HandleException]
    [CheckModelForNull]
    [ValidateModelState]
    public object Post([FromBody]User user) 
    {    
        var asd = 0;
        var qwe = 1 / asd;
        return new HttpStatusCodeResult(HttpStatusCode.OK);
    }
}

Solution

  • ApiControllers do not use HandleErrorAttribute

    Should better use ExceptionFilterAttribute

    public class NotImplExceptionFilterAttribute : ExceptionFilterAttribute 
    {
        public override void OnException(HttpActionExecutedContext context)
        {
           log.error("ERROR",context.Exception);
        }
    }
    

    http://www.asp.net/web-api/overview/web-api-routing-and-actions/exception-handling