在网页API 2.2 OWIN中间件异常处理程序替换IExceptionHandler

问题描述:

我已经创建了一个OWIN中间件来捕获异常。中间件并没有什么,但换用尝试捕捉类似这样

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
}

问题是,middlware未捕获异常,因为异常是被IExceptionHandler的默认实现返回的堆栈跟踪的XML处理。

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.

我知道我可以用我自己的替换默认IExceptionHandler实现,但我想要的是OWIN中间件来采取控制和被忽略,或与OWIN中间件替代这个默认的异常处理

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

更新:

我已经打上了以下答案的答案,尽管它更是一个黑客,但我真的相信是没有办法可以实现这一点没有一个黑客,因为的WebAPI异常永远不会被OWIN中间件被抓,因为Web API处理自己例外而OWIN中间件处理这是在中间件提出,而不是处理的异常/这些中间件陷入

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

请一个的ExceptionHandler:IExceptionHandler像在这个答案一>。然后在HandleCore,采取例外,它推到OwinContext:

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
    }
}