最佳实践:如何处理web api控制器中的错误和异常?

Yas*_*ser 20 asp.net-mvc asp.net-mvc-4 asp.net-web-api

我正在开发一个项目,并且在所有客户端操作上都非常依赖web api,无论是帐户详细信息更新,添加了新的详细信息,还是使用ASP.NET Web Api和Backbone.js修改了所有内容.

当前场景:

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

示例:

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

所以在对此操作进行ajax调用后,我检查响应是否为true/false并显示错误或成功消息.

问题:

现在发生的事情是我开始在我的操作中获得异常,并且操作保持返回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; }
}
Run Code Online (Sandbox Code Playgroud)

这种变化将是一个重大变化,耗费时间和资源,所以我认为最好对此有第二/第三/第四意见.

请对此有所了解.

更新:

对于一些小的帮助,从马克·琼斯,我想出了这个

[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;
}
Run Code Online (Sandbox Code Playgroud)

有什么想法吗?

Fil*_*p W 26

您应该避免在控制器的操作中使用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"
        });
    }
}
Run Code Online (Sandbox Code Playgroud)

然后你可以装饰你的动作[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的异常处理技术.