使用 ASP.NET Web API 处理错误的最佳实践 [英] Best practice for error handling with ASP.NET Web API

查看:16
本文介绍了使用 ASP.NET Web API 处理错误的最佳实践的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您能否阐明 Web API 错误管理的最佳实践是什么.实际上,我不知道在我的 Api 请求中使用 try catch 是否是一个好习惯.

Could you clarify what is the best practice with Web API error management. Actually, I don't know if it is a good practice to use try catch into my Api request.

public Vb.Order PostOrderItem(Vb.Order order)
{
    if (OAuth.isValid(Request.Headers.GetValues("Token").Single()) != true)
    {
        HttpResponseMessage httpResponseMessage = new HttpResponseMessage(HttpStatusCode.Unauthorized);
        throw new HttpResponseException(httpResponseMessage);
    }
    if (!ModelState.IsValid)
    {
        HttpResponseMessage httpResponseMessage = new HttpResponseMessage(HttpStatusCode.BadRequest);
        throw new HttpResponseException(httpResponseMessage);
    }

    try
    {
        return Vb.Document.Generate(order);
    }
    catch (Exception ex)
    {
        logger.Error(ex);
        HttpResponseMessage httpResponseMessage = new HttpResponseMessage(HttpStatusCode.BadRequest);
        httpResponseMessage.Content = new StringContent(ex.Message);
        throw new HttpResponseException(httpResponseMessage);
    }

}

我觉得对服务器端代码使用 try catch 不是一个好习惯,因为我只是记录我的 catch 并重新抛出异常.

I have the feeling using try catch to a server side code is not a good practice because I just log my catch en re-throw an exception.

推荐答案

Web API 中的错误处理被认为是一个交叉问题,应该放在管道中的其他地方,这样开发人员就不需要关注交叉问题消除顾虑.

Error handling in Web API is considered a cross-cutting concern and should be placed somewhere else in the pipeline so the developers doesn’t need to focus on cross-cutting concerns.

您应该阅读ASP.NET Web API 中的异常处理

如果 Web API 控制器抛出未捕获的异常会怎样?经过默认情况下,大多数异常被转换为 HTTP 响应状态码 500,内部服务器错误.

What happens if a Web API controller throws an uncaught exception? By default, most exceptions are translated into an HTTP response with status code 500, Internal Server Error.

以及ASP.NET Web API 中的全局错误处理2

您应该尽量保持控制器的精简.像原始代码一样处理错误只会导致代码重复,以及开发人员需要注意的不必要的问题.开发人员应该关注核心问题,而不是跨领域的问题.通过只关注核心问题,上面的代码将如下所示:

You should try to keep your controller lean as much as possible. Error handling like your original code will only result in duplication of code, and unnecessary concerns for the developers to be aware of. Developers should focus on the core-concern, not the cross-cutting concerns. By just focusing on the core-concern the above code will look like this:

[MyAuthentication]
[MyValidateModel]
public Vb.Order PostOrderItem(Vb.Order order)
{    
    return Vb.Document.Generate(order);
}

为什么这么瘦?

因为:

if (OAuth.isValid(Request.Headers.GetValues("Token").Single()) != true)
{
    HttpResponseMessage httpResponseMessage = new HttpResponseMessage(HttpStatusCode.Unauthorized);
    throw new HttpResponseException(httpResponseMessage);
}

可以移动到 ASP.NET Web API 2 中的身份验证过滤器可以在控制器/操作上本地应用或全局应用以返回相关响应.

can be moved into Authentication Filters in ASP.NET Web API 2 that can be applied locally on the controller/action or globally to return a relevant response.

ASP 中的模型验证.NET Web API 像这样

if (!ModelState.IsValid)
{
    HttpResponseMessage httpResponseMessage = new HttpResponseMessage(HttpStatusCode.BadRequest);
    throw new HttpResponseException(httpResponseMessage);
}

也可以移动到过滤器中,例如:.

Can also be moved into a filter like : .

public class MyValidateModelAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(HttpActionContext actionContext)
    {
        if (!actionContext.ModelState.IsValid)
        {
            actionContext.Response = actionContext.Request.CreateErrorResponse(
                HttpStatusCode.BadRequest, actionContext.ModelState);
        }
    }
}

这篇关于使用 ASP.NET Web API 处理错误的最佳实践的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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