【问题标题】:Exceptions not caught in my OwinMiddleware我的 OwinMiddleware 中未捕获的异常
【发布时间】:2018-01-19 12:30:07
【问题描述】:

我创建了一个 OwinMiddleware 来捕获我的 api 请求中所有未处理的异常。

 public class UnhandledExceptionMiddleware : OwinMiddleware
{
    private static readonly Logger logger = LogManager.GetCurrentClassLogger();

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

    public override async Task Invoke(IOwinContext context)
    {
        try
        {
            await Next.Invoke(context);                
        }
        catch (Exception ex)
        {
            logger.Fatal(ex, ex.Message);
        }
    }
}

但是,如果我在控制器函数中抛出一些错误,则不会使用 catch 块,并且在这个中间件中似乎一切都很好。为什么我的 catch 块没有被使用?

更新

这是我的 Owin 配置。调用方法仅在 catch 不起作用时起作用

public void Configuration(IAppBuilder app)
    {
        
        // Enables use of spatial data types
        SqlServerTypes.Utilities.LoadNativeAssemblies(HostingEnviron‌​ment.MapPath("~/bin"));

        HttpConfiguration config = new HttpConfiguration();
        IContainer container = AutoFacConfig.Register(config, app);

        app.UseApplicationInsights();
        app.UseNLog();
        app.Use<UnhandledExceptionMiddleware>();

【问题讨论】:

标签: c# asp.net-web-api owin


【解决方案1】:

中间件按照它们添加到管道的顺序被调用。确保在这种情况下,UnhandledExceptionMiddleware 在启动期间添加在任何其他之前

public class Startup {
    public void Configuration(IAppBuilder app) {

        app.Use<UnhandledExceptionMiddleware>();

        //...Add other middleware

        //...code removed for brevity
    }
} 

【讨论】:

    【解决方案2】:

    通过这篇文章解决了。 Disable *all* exception handling in ASP.NET Web API 2 (to make room for my own)?

    您必须覆盖默认的 IExceptionFilter 才能在中间件中捕获异常。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-06-21
      • 2013-06-04
      • 2023-03-26
      • 1970-01-01
      • 2010-09-28
      • 2012-05-31
      相关资源
      最近更新 更多