سؤال

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);
    }
}
هل كانت مفيدة؟

المحلول

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

نصائح أخرى

As noted in a comment, Filter attributes only apply to actions in controllers. If you want to also capture errors from other classes or something that happens before the code enters an action, you need to overwrite Application_Error method in Global.asax:

protected void Application_Error(object sender, EventArgs e)
{
    log.Info("inside on exception"); 
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top