【问题标题】:Best Practice : Ways to handle errors and exception in web api controllers?最佳实践:在 web api 控制器中处理错误和异常的方法?
【发布时间】:2012-12-19 23:29:50
【问题描述】:

我正在做一个项目,我的所有客户端操作都严重依赖 web api,无论是帐户详细信息更新、添加新详细信息、修改所有内容都已使用 ASP.NET Web Api 和 Backbone.js 完成

p>

当前场景:

在当前的方案中,我从我的 web api 控制器返回一个布尔值,以指示操作是否成功。

例子:

[ActionName("UpdateAccountDetails")]
public bool PostAccountDetails(SomeModel model)
{
    bool updateStatus = _customService.UpdateAccountDetails(model);
    return updateStatus;
}

因此,在对此操作进行 ajax 调用后,我会检查响应的真/假并显示错误或成功消息。

问题:

现在发生的事情是我的操作开始出现异常,并且操作一直返回 false,并且显示了错误消息。但我找不到原因?

所以我想知道是否有每个人都遵循的标准 api 响应结构?

我最初提出这个想法是让每个 web api 操作都返回这个类

public class OperationStatus
{
    public bool Result { get; set; } // true/false
    public string Status { get; set; } // success/failure/warning
    public List<string> WarningMessages { get; set; }
    public List<string> ErrorMessages { get; set; }
    public string OtherDetails { get; set; }
}

此更改将是一项重大更改,并且会耗费时间和资源,因此我认为最好对此有第二/第三/第四意见。

请对此提出一些想法。

更新:

有了来自Mark Jones 的一些little help,我想出了这个

[ActionName("UpdateAccountDetails")]
public HttpResponseMessage PostAccountDetails(SomeModel model)
{
    bool updateStatus;
    string errorMessage;
    try{
        updateStatus = _customService.UpdateAccountDetails(model);
        if(updateStatus)
        {
            return Request.CreateResponse(HttpStatusCode.OK);
        }
        return Request.CreateResponse(HttpStatusCode.InternalServerError);
    }
    catch(Exception exception)
    {
        errorMessage = exception.Message;
        return Request.CreateResponse(HttpStatusCode.InternalServerError, errorMessage);
    }

    return updateStatus;
}

对此有什么想法吗?

【问题讨论】:

  • 这篇文章可能会给你一些关于使用 WebAPI 实现错误处理的想法:blogs.msdn.com/b/youssefm/archive/2012/06/28/…
  • 您还应该看看下面凯文和菲利普的建议。实现异常过滤器是一个好主意,您应该考虑在发生错误时抛出 HttpResponseException,这样您就不必更改操作签名上的返回类型。

标签: asp.net-mvc asp.net-mvc-4 asp.net-web-api


【解决方案1】:

您应该避免在控制器的操作中使用 try/catch。

有很多方法可以解决您的问题。 最简单和最干净的解决方案可能是使用ActionFilter 来处理异常,类似于:

public class ExceptionAttribute : ExceptionFilterAttribute
{
    public override void OnException(HttpActionExecutedContext context)
    {
        Debug.WriteLine(context.Exception);

        throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)
        {
            Content = new StringContent("An error occurred!"),
            ReasonPhrase = "Deadly Exception"
        });
    }
}

然后你可以用[ExceptionAttribute]来装饰你的动作。 当然,您可以将其扩展为针对不同类型的异常(业务异常、数据异常、IO 异常等)表现出不同的行为,并基于此返回不同的状态码和反馈。

我建议您阅读 Fredrik Normen 的 优秀文章 - “ASP.NET Web API 异常处理” http://weblogs.asp.net/fredriknormen/archive/2012/06/11/asp-net-web-api-exception-handling.aspx

他对 Web API 的异常处理技术进行了很好的概述。

【讨论】:

  • 优秀的推荐,感谢您发布有关 Fredrik Normen 的文章!
【解决方案2】:

我不会返回 HttpResponseMessage,而是保持 API 不变,并在捕获异常时抛出 HttpResponseException。像这样的:

throw new HttpResponseException(
    new HttpResponseMessage(HttpStatusCode.InternalServerError) 
       { ReasonPhrase = errorMessage });

这样您就不会更改 API 的定义,并且它也适用于您的 GET 操作,您可以在其中返回一些必须序列化的对象。如果您使用 JQuery ajax 方法来发送请求,那么您的 error 处理程序将捕捉到这一点,您可以在 errorThrown 参数中检索文本消息并相应地处理它。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-01-07
    • 2013-09-01
    • 2018-01-03
    • 1970-01-01
    • 1970-01-01
    • 2016-10-27
    • 2017-05-11
    相关资源
    最近更新 更多