Replace IExceptionHandler in Web Api 2.2 with OWIN

2019-03-19 23:19发布

问题:

I have created an OWIN middleware to catch exceptions. The middleware does nothing really but wrap the next call with try catch like this

try {
  await _next(environment)
}
catch(Exception exception){
 // handle exception
}

The problem is that the middlware is not capturing the exception because the exception is been handled by the default implementation of IExceptionHandler which returns an xml with the stack trace.

I understand that I can replace the default IExceptionHandler implementation with my own but what I want is for OWIN middleware to take control and this default exception handler to be ignored or replaced with the OWIN middleware

Update:

I have marked the below answer as an answer although it is more of a hack but I truly believe there is no way you can achieve this without a hack because WebApi exceptions will never be caught by OWIN middleware because Web API handle its own exceptions whereas OWIN middleware handles exceptions which are raised in middlewares and not handled/caught by these middlewares

回答1:

Make an "ExceptionHandler : IExceptionHandler" like in this answer. Then in HandleCore, take that exception and shove it into the OwinContext:

public void HandleCore(ExceptionHandlerContext context)
{
    IOwinContext owinContext = context.Request.GetOwinContext();
    owinContext.Set("exception", context.Exception);
}

Then in your middleware, check if the Environment contains the "exception" key.

public override async Task Invoke(IOwinContext context)
{
    await Next.Invoke(context);

    if(context.Environment.ContainsKey("exception")) {
        Exception ex = context.Environment["exception"];
        // Do stuff with the exception
    }
}