且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

未处理的异常处理程序全球对OWIN /武士刀?

更新时间:2023-02-15 22:45:48

尝试编写自定义的中间件,并把它作为第一中间件:

Try writing a custom middleware and placing it as the first middleware:

public class GlobalExceptionMiddleware : OwinMiddleware
{
   public GlobalExceptionMiddleware(OwinMiddleware next) : base(next)
   {}

   public override async Task Invoke(IOwinContext context)
   {
      try
      {
          await Next.Invoke(context);
      }
      catch(Exception ex)
      {
          // your handling logic
      }
   }
 }

把它作为第一中间件:

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

        builder.Use<GlobalExceptionMiddleware>();
        //register other middlewares
    }
}

当我们注册这个中间件作为第一中学,在其他中间件发生(下堆栈跟踪)的任何异常将传播并通过的的try / catch 块被抓这个中间件。

When we register this middleware as the first middle, any exceptions happening in other middlewares (down the stacktrace) will propagate up and be caught by the try/catch block of this middleware.

这不是强制性总是把它注册为第一个中间件,如果你不需要全局异常处理一些中间件,这种一前刚刚注册这些中间件。

It's not mandatory to always register it as the first middleware, in case you don't need global exception handling for some middlewares, just register these middlewares before this one.

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

            //register middlewares that don't need global exception handling. 
            builder.Use<GlobalExceptionMiddleware>();
            //register other middlewares
        }
    }