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
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
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With