使用ASP.NET Web API进行错误处理的最佳做法 [英] Best practice for error handling with ASP.NET Web API

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

问题描述

你能澄清一下Web API错误管理的最佳做法。实际上,我不知道在我的Api请求中使用try catch是个好习惯。

  public Vb.Order PostOrderItem(Vb.Order order)
{
if(OAuth.isValid(Request.Headers.GetValues(Token)。Single())!= true)
{
HttpResponseMessage httpResponseMessage = new HttpResponseMessage(HttpStatusCode.Unauthorized);
抛出新的HttpResponseException(httpResponseMessage);
}
if(!ModelState.IsValid)
{
HttpResponseMessage httpResponseMessage = new HttpResponseMessage(HttpStatusCode.BadRequest);
抛出新的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);
抛出新的HttpResponseException(httpResponseMessage);
}

}

我有感觉使用try catch服务器端的代码不是一个好的做法,因为我只是记录我的catch,重新抛出异常。

解决方案

错误处理在Web API中被认为是一个交叉关切的问题,应该放在其他地方,所以开发人员不需要关注交叉关切。



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


如果Web API控制器引发未捕获的异常,会发生什么?通过
默认,大多数异常都被转换为HTTP响应,
状态码为500,内部服务器错误。


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



你应该尽量保持你的控制器精益求精。像原始代码一样处理错误只会导致重复的代码,并且不必要的开发人员的注意事项。开发人员应着重于核心关注,而不是横向关切。通过关注核心关注,上述代码将如下所示:

  [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);
抛出新的HttpResponseException(httpResponseMessage);
}

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



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

  if(!ModelState .IsValid)
{
HttpResponseMessage httpResponseMessage = new HttpResponseMessage(HttpStatusCode.BadRequest);
抛出新的HttpResponseException(httpResponseMessage);
}

也可以移动到如下所示的过滤器中:

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


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

}

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.

解决方案

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.

You should take a read of Exception Handling in ASP.NET Web API

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.

and also Global Error Handling in 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);
}

Why so lean?

Because :

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

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.

Model Validation in ASP.NET Web API like this

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天全站免登陆