asp web api中的异常处理

本文关键字:异常处理 api web asp | 更新日期: 2023-09-27 18:05:25

我想要一个方法来捕获我的asp.net web api项目中所有未处理的异常。我发现这篇文章:我如何记录所有异常全局c# MVC4 WebAPI应用程序?它讨论了使用ExceptionFilterAttribute和OnException。

这是工作到目前为止,我能够捕捉在api控制器中抛出的异常,然后识别异常。然后,我想抛出一个带有StatusCode和特定于我捕获的原始异常的内容的HttpResponseException。我该怎么做呢?

这是我目前所拥有的:

public override void OnException(HttpActionExecutedContext context) {
    HttpResponseMessage msg = new HttpResponseMessage();
    if (context.Exception.GetType() == typeof(DBAccess.DeleteNotAllowed)) {
        msg.StatusCode = HttpStatusCode.Forbidden;
        msg.Content = new StringContent("Illegal action");
        msg.ReasonPhrase = "Exception";
        throw new HttpResponseException(msg);
    } else {
        //handle next exception type
    }
}

当抛出deletenotalallowed异常时,它会被捕获,并将错误消息发送给客户端。但是,在else语句处抛出另一个异常。

asp web api中的异常处理

最好的方法是使用Elmah。

这是我自2010年以来一直在使用的最好的工具之一。它是异常处理最有用的工具。它还将为您提供一个很好的易于使用的界面,以查看web, e-amil和db的错误。

详情请参阅:http://blogs.msdn.com/b/webdev/archive/2012/11/16/capturing-unhandled-exceptions-in-asp-net-web-api-s-with-elmah.aspx

据我所知,您想将所有服务器端异常翻译成更易于阅读和有意义的异常吗?如果这是你想要的,那么你有两个选择,为所有可能的异常类型写if/elsetry/catch,这将违反OCP -开闭原则,而不是这样,我建议你这种方法:让每个异常决定它自己的"翻译"客户端,在OnException中捕获它们,并返回到客户端消息和具体异常给出的状态代码。

    public class ApiException : Exception
    {
        public int FaultCode { get; private set; }
        public ApiException(int faultCode, string message)
            : base(message)
        {
            this.FaultCode = faultCode;
        }
    }

正如你所看到的,它有FaultCodeMessage(从基础Exception继承)属性,它的构造函数需要从ApiException的每个具体实实者传递它自己的状态代码和消息(那些你将在OnException方法中稍后翻译)。

    public override void OnException(HttpActionExecutedContext context)
    {
        HttpResponseMessage msg = new HttpResponseMessage();
        if (context.Exception is ApiException)
        {
            ApiException apex = context.Exception as ApiException;
            msg.StatusCode = apex.StatusCode;
            msg.Content = new StringContent(apex.Message);
            throw new HttpResponseException(msg);
        }
    }

这就是你的OnException方法的样子