最佳实践:的方式来处理在网页API控制器错误和异常? [英] Best Practice : Ways to handle errors and exception in web api controllers?

查看:133
本文介绍了最佳实践:的方式来处理在网页API控制器错误和异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我工作的一个项目,并已严重依赖于网络API为我所有的客户端的操作,无论是帐户的详细信息的更新,新的细节补充,修改一切都已经做了与ASP.NET网页API和Backbone.js的

I am working on a project and have relied heavily on web api for all my client side operations, be it account details update, new details added, modify everything has been done with ASP.NET Web Api and Backbone.js

当前场景:

在当前事物的计划,我从我的网页API返回的控制器一个布尔值,指示操作是否全成与否。

In the current scheme of things, I am returning a boolean value from my web api controllers, to indicate whether the operation was successfull or not.

例如:

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

所以要实现AJAX调用这个动作后,我检查真/假并显示错误或成功的消息的响应。

so after making an ajax call to this action, I check the response for true/false and display error or success messages.

问题:

现在发生了什么事,我开始在我的行动变得异常,动作保持返回false,并显示错误消息。但我没能找到,为什么?

Now what happened was I started getting exceptions in my action, and the action kept returning false, and the error message was shown. But I was not able to find why ?

所以我在想,如果有每个人遵循它的标准API响应结构?

So I was wondering if there is a standard api response structure which every one follows ?

我最初想出这个主意,有每个Web API的行动来回报这个类

I had initially come up with this idea to have each web api action to return this class

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; }
}

这个变化将是一个重大的变化,并会耗费时间和资源,所以我认为它能够更好地对这个第二/第三/第四个意见。

This change would be a major change and would be time and resource consuming, so I thought its better to have a second/third/fourth opinion on this.

请把一些想法这一点。

更新:

对于某些一点帮助 http://stackoverflow.com/users/1440706/mark -jones>标记琼斯,我想出了这个

With some little help from Mark Jones, I have come up with this

[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;
}

对此有何想法?

推荐答案

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

You should avoid using try/catch in the controller's action.

有很多方法来处理你的问题。
最简单和最干净利落的解决方案可能会使用一个 ActionFilter 来处理异常,沿着线的东西:

There are many ways to handle your problem. The simplest and cleanest solution would probably be to use an ActionFilter to handle the exceptions, something along the lines of:

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异常等,并返回基于不同的状态codeS和反馈,以及

Then you can just decorate your action with [ExceptionAttribute]. Of course you can extend that to behave differently for different types of exceptions - business exceptions, data exceptions, IO exceptions and so on, and return different status codes and feedback based on that as well.

我建议你由Fredrik诺门读精彩文章 - 的ASP.NET Web API异常处理的<一个href=\"http://weblogs.asp.net/fredriknormen/archive/2012/06/11/asp-net-web-api-exception-handling.aspx\">http://weblogs.asp.net/fredriknormen/archive/2012/06/11/asp-net-web-api-exception-handling.aspx.

I recommend you read an excellent article by Fredrik Normen - "ASP.NET Web API Exception Handling" http://weblogs.asp.net/fredriknormen/archive/2012/06/11/asp-net-web-api-exception-handling.aspx.

他提供了异常处理技术的很好的概述的Web API。

He provides a great overview of exception handling techniques for Web API.

这篇关于最佳实践:的方式来处理在网页API控制器错误和异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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