gpt4 book ai didi

c# - 使用 ASP.NET Web API 进行错误处理的最佳实践

转载 作者:IT王子 更新时间:2023-10-29 04:32:27 26 4
gpt4 key购买 nike

您能否阐明 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);
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 并重新抛出异常。

最佳答案

Web API 中的错误处理被认为是一个横切关注点,应该放在管道中的其他地方,这样开发人员就不需要关注横切关注点。

你应该读一读 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.

还有Global Error Handling in ASP.NET Web API 2

您应该尽量保持您的 Controller 精简。像您的原始代码那样进行错误处理只会导致代码重复,并让开发人员意识到不必要的担忧。开发人员应该关注核心问题,而不是横切问题。通过只关注核心问题,上面的代码将如下所示:

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

可移入Authentication Filters in ASP.NET Web API 2 可以在 Controller /操作上局部应用或全局应用以返回相关响应。

Model Validation in ASP.NET Web API像这样

if (!ModelState.IsValid)
{
HttpResponseMessage httpResponseMessage = new HttpResponseMessage(HttpStatusCode.BadRequest);
throw new 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);
}
}
}

关于c# - 使用 ASP.NET Web API 进行错误处理的最佳实践,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38025305/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com