不调用全局异常处理程序

时间:2016-06-01 09:48:12

标签: c# exception-handling asp.net-web-api2 owin

我试图创建一个oWin中间件类,它将捕获堆栈中的所有异常,并适当地处理它们。甲

this篇文章之后,我创建了一个IExceptionHandler类,将异常从WebApi传递到中间件堆栈。

但是,这似乎不起作用。虽然调用了HandleCore方法,并且info.Throw()被命中,但异常内容从未出现在Middleware类中。

的ExceptionHandler

public class WebApiExceptionPassthroughHandler : ExceptionHandler
{
    public override Task HandleAsync(ExceptionHandlerContext context, CancellationToken cancellationToken)
    {
        HandleCore(context);

        return Task.FromResult(0);
    }

    public override void Handle(ExceptionHandlerContext context)
    {
        HandleCore(context);
    }

    private void HandleCore(ExceptionHandlerContext context)
    {
        //Pass webAPI Exceptions up the stack to the Logging Middleware - which will handle all exceptions.
        if (!ShouldHandle(context)) return;

        var info = ExceptionDispatchInfo.Capture(context.Exception);
        info.Throw();
    }

    public override bool ShouldHandle(ExceptionHandlerContext context)
    {
        return context.ExceptionContext.CatchBlock.IsTopLevel;
    }
}

启动

public class Startup
{
    public void Configuration(IAppBuilder app)
    {
        app.Use<LoggingMiddleware>();

        GlobalConfiguration.Configure(WebApiConfig.Register);
        app.UseWebApi(GlobalConfiguration.Configuration);
    }
}

LoggingMiddleware

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

    public override async Task Invoke(IOwinContext context)
    {


        //TODO: Initialise the log
        try
        {
            await Next.Invoke(context);
        }
        catch (System.Exception ex)
        {
            //This is not getting reached.
            var i = 1;
        }
    }
}

在webapi.config中,我有这个命令:

config.Services.Replace(typeof(IExceptionHandler), new WebApiExceptionPassthroughHandler());

如何让webApi异常冒泡到Middleware日志记录类?

1 个答案:

答案 0 :(得分:1)

如果你想转移到Owin摆脱那个坏System.WebGlobalConfiguration。尝试在Startup中创建Api配置。

public class Startup
{
    public void Configuration(IAppBuilder app)
    {
        app.Use<LoggingMiddleware>();


        var config = new HttpConfiguration();
        //Move your WebApiConfig.Register here
        config.Services.Replace(typeof(IExceptionHandler), new WebApiExceptionPassthroughHandler())

        //Finally use your newly created config here
        app.UseWebApi(config);
    }
}

希望它有所帮助。