【问题标题】:Web API 2 return an error and make http.post catch itWeb API 2 返回错误并让 http.post 捕获它
【发布时间】:2017-07-14 18:23:13
【问题描述】:

到目前为止,如果发生 web api 2 错误并且我捕获了它,我会返回一个自定义对象并从捕获中填写错误消息。然而,这会使实际的 http.post() 进入成功方法而不是错误,然后我必须查看我自己的布尔成功变量,如果为真则一切都好,如果为假则显示错误。这有点烦人,因为出于 2 个不同的原因,我必须在 2 个不同的地方查找错误。从 Web API 2 开始,如果我在 Web api 控制器中发现错误,我是否可以让 http.post() 在填写错误消息时触发错误回调?

[HttpPost]
public MyResponseObject UpdateData(RequestObject req)
{
   MyResponseObject resp = new MyResponseObject();
   resp.Success = true;

   try{
      // error happens here
   }catch(Exception ex){
      resp.Success = false;
      resp.Msg = ex.Message;
   }

   return resp;
}

http.post() 调用仍然会成功,但现在我必须查看我的 resp.Success 的成功回调,看看它是否真的成功。确实可以进行 API 调用,但其中出现了问题。我希望能够显示该消息并使调用失败,以便使用异常消息调用 http.post() 错误回调。

【问题讨论】:

  • 未捕获异常应触发此行为。或者你可以抓住它,记录有用的信息,然后抛出一个HttpResponseException 并带有最终用户友好的消息。

标签: c# asp.net-web-api2


【解决方案1】:

只要抛出一个异常:

throw new HttpResponseException(HttpStatusCode.InternalServerError);

如果您想自定义返回的响应,您可以创建一个HttpResponseMessage 并提供更多详细信息:

var response = new HttpResponseMessage(HttpStatusCode.InternalServerError)
{
    Content = new StringContent("We messed up"),
    ReasonPhrase = "Error"
}
throw new HttpResponseException(resp);

文档here

【讨论】:

  • 非常感谢。使我无需创建自定义响应对象。
猜你喜欢
  • 2015-10-01
  • 2015-04-07
  • 1970-01-01
  • 1970-01-01
  • 2018-07-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多