2

我正在尝试添加一些中间件,以便我捕获并记录任何未处理的异常,但在这样做时遇到了一些困难。在这方面找不到很多东西,出于某种奇怪的原因,我的代码似乎没有进入 catch 块。似乎它正在优雅地处理这个甚至询问我看不到异常的字典。

我想要发生的是,进入 catch 块抓取异常并记录堆栈跟踪。

编码:

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

        app.Use(typeof(FooHandler));
        app.UseWebApi(config);
    }
}

public class FooHandler : OwinMiddleware
{
    private static readonly ILog Logger = LogManager.GetLogger(typeof(FooHandler));

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

    public override async Task Invoke(IOwinContext context)
    {
        if (Logger.IsErrorEnabled)
        {
            try
            {
                await Next.Invoke(context);
            }
            catch (Exception ex)
            { // DOESN'T FALL INTO HERE!
                Logger.Error(message, ex);
            }
        }
    }
}

public class FooController : ApiController
{        
    public Task<IHttpActionResult> Get()
    {
        throw new Exception("Foo Bar");
    }
}   
4

1 回答 1

0

这是因为 WebApi 正在处理异常。您将需要处理控制器抛出的异常ExceptionFilterAttribute

于 2016-02-16T21:55:19.720 回答