网页API OWIN启动异常处理 [英] Web API OWIN startup exception handling

查看:456
本文介绍了网页API OWIN启动异常处理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的C#的Web API,我试图添加全局异常处理程序。我一直在使用一个自定义全局 ExceptionFilterAttribute 来处理异常和返回 HttpResponseMessage

In my C# Web API, I'm trying to add a global exception handler. I've been using a custom global ExceptionFilterAttribute to handle the exception and return a HttpResponseMessage:

public override void OnException(HttpActionExecutedContext context)
{
    ...

    const string message = "An unhandled exception was raised by the Web API.";
    var httpResponseMessage = new HttpResponseMessage(HttpStatusCode.InternalServerError)
    {
        Content = new StringContent(message),
        ReasonPhrase = message
    };
    context.Response = httpResponseMessage;
}

这一直很好处理在控制器级别抛出异常。

This has worked fine for handling exceptions thrown at the controller level.

不过,在开发过程中,我们必须从我们的OWIN启动文件引发的错误由于数据库连接的问题,然而,一个标准的IIS异常返回,而不是通过全球的异常处理程序去,以及完整的HTML返回到我们的API消费者

However, during development we had an error thrown from our OWIN startup file due to a database connection issue, however, a standard IIS exception was returned, instead of going through the global exception handler, and the full HTML was returned to our API consumer.

我已经尝试了几种不同的方法来捕捉我OWIN启动抛出的异常:

I've tried a few different approaches to catch exceptions thrown in my OWIN startup:

自定义 ApiControllerActionInvoker

public class CustomActionInvoker : ApiControllerActionInvoker
{
    public override Task<HttpResponseMessage> InvokeActionAsync(HttpActionContext actionContext, CancellationToken cancellationToken)
    {
        var result = base.InvokeActionAsync(actionContext, cancellationToken);

        if (result.Exception != null && result.Exception.GetBaseException() != null)
        {
            ...
        }

        return result;
    }
}



自定义的ExceptionHandler

public class CustomExceptionHandler : ExceptionHandler
{
    public override void Handle(ExceptionHandlerContext context)
    {
        ...

        base.Handle(context);
    }

    public override bool ShouldHandle(ExceptionHandlerContext context)
    {
        return true;
    }
}



自定义 OwinMiddleware 组件:

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

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

和最后只是用的Application_Error

protected void Application_Error(object sender, EventArgs e)
{
    ...
}

但似乎没有捕捉异常。

有谁知道一个办法赶上异常,并返回一个 HttpResponseMessage ?或者,如果任何我已经尝试应该有工作的办法?

Does anyone know of a way to catch the exception and return a HttpResponseMessage? Or if any of the approaches I've already tried should have worked?

任何帮助非常赞赏。

推荐答案

我有一个正确地做到这一点的应用程序。在我来说,我写了一个中间件类,它总是返回一条消息,告诉来电者,该服务不可用,因为有启动过程中出现错误。这个类是在我的解决方案名为 FailedSetupMiddleware 。它的外形看起来像这样:

I have an application that does this correctly. In my case I wrote a middleware class that always returns a message telling the caller that the service is unavailable because there was an error during startup. This class is called FailedSetupMiddleware in my solution. The outline of it looks like this:

public class FailedSetupMiddleware
{
    private readonly Exception _exception;

    public FailedSetupMiddleware(Exception exception)
    {
        _exception = exception;
    }

    public Task Invoke(IOwinContext context, Func<Task> next)
    {
        var message = ""; // construct your message here
        return context.Response.WriteAsync(message);
    }
}

在我的配置类我有一个的try ... catch 模块,与配置OWIN管道只有 FailedSetupMiddleware 。在一个例外是在配置过程中抛出的情况下

In my Configuration class I have a try...catch block that configures the OWIN pipeline with only the FailedSetupMiddleware in the case where an exception was thrown during configuration.

我OWIN启动类看起来是这样的:

My OWIN startup class looks like this:

[assembly: OwinStartup(typeof(Startup))]

public class Startup
{
    public void Configuration(IAppBuilder app)
    {
        try
        {
            //
            // various app.Use() statements here to configure
            // OWIN middleware
            //
        }
        catch (Exception ex)
        {
          app.Use(new FailedSetupMiddleware(ex).Invoke);
        }
    }
}

这篇关于网页API OWIN启动异常处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆