2

I am trying to add some middleware so that any unhandled exceptions I catch and log it but experiencing some difficulties in doing so. Not been able to find a lot on this and for some odd reason my code doesn't seem to be entering the catch block. Seems like it is gracefully handling this and even interrogating the dictionary I can't see the exception.

What I want to happen is, enter the catch block grab the exception and log the stack trace.

The code:

public class Startup
{
    public void Configuration(IAppBuilder app)
    {
        var config = new HttpConfiguration();

        app.Use(typeof(FooHandler));
        app.UseWebApi(config);
    }
}

public class FooHandler : OwinMiddleware
{
    private static readonly ILog Logger = LogManager.GetLogger(typeof(FooHandler));

    public FooHandler(OwinMiddleware next) : base(next)
    {
    }

    public override async Task Invoke(IOwinContext context)
    {
        if (Logger.IsErrorEnabled)
        {
            try
            {
                await Next.Invoke(context);
            }
            catch (Exception ex)
            { // DOESN'T FALL INTO HERE!
                Logger.Error(message, ex);
            }
        }
    }
}

public class FooController : ApiController
{        
    public Task<IHttpActionResult> Get()
    {
        throw new Exception("Foo Bar");
    }
}   
Dr Schizo
  • 4,045
  • 7
  • 38
  • 77

1 Answers1

0

This is because WebApi is handling the exception. You will need to handle exceptions thrown by Controllers in an ExceptionFilterAttribute

Ethan Cabiac
  • 4,943
  • 20
  • 36