【问题标题】:Return CreateErrorResponse or throw new HttpResponseException返回 CreateErrorResponse 或抛出新的 HttpResponseException
【发布时间】:2016-03-14 04:20:36
【问题描述】:

我是 Web API 的新手(在 VS 2012 中使用 C#)并试图帮助一个项目,该项目涉及将更有意义的错误返回到 AngularJS 前端,但我不确定是否有关于以下方面的首选方法只是捕捉到错误并说

return Request.CreateErrorResponse(..

对比

throw new HttpResponseException(Request.CreateErrorResponse(...

我不完全了解返回响应错误的优缺点或用途。

关于更多背景知识,我们正在上传 Excel 文件,并且我们有各种在解析等时会导致错误的用例。我想异步返回错误消息,以明确导致错误的原因,而不是模棱两可的“异常”。

所以我正在尝试诸如

try 
{
//stuff
}
catch (FormatException e)
{
   return  Request.CreateErrorResponse(HttpStatusCode.Conflict, "issue 1");
}
catch (FileFormatException e)
{
   return  Request.CreateErrorResponse(HttpStatusCode.Conflict, "issue 2");
}
catch (Exception ex)
{
   return  Request.CreateErrorResponse(HttpStatusCode.Conflict, "issue 3");
}

我可以给错误赋予更多的意义。我只是对是否应该“返回”Request.CreateErrorResponse 或“抛出”像 throw new HttpResponseException(Request.CreateErrorResponse(... 这样的异常感到困惑

在前端我只是读回那个错误

.error(function (data) {
        $scope.uploadFailed = true;     //shows the message span
        $scope.uploadMsg = data["Message"].trim();
 });

如果这令人困惑,请原谅我,我只是想确定哪种返回错误的方式最适合这种情况以及原因。

【问题讨论】:

    标签: angularjs exception-handling httpresponse asp.net-web-api


    【解决方案1】:

    我很惊讶迄今为止没有人回答这个问题......基本上你是在问, How much more expensive is an Exception than a return value?

    从性能的角度来看,您最好返回错误响应。

    一般来说,我建议尽可能避免抛出异常,尤其是在您期望它们的情况下。例外应该是例外情况。

    根据经验,我会说,如果您使用客户端错误 (4XX),它们并不例外,因为您已经预测到它们,例如,在适当的时候,您可以 TryParse 然后返回 400 BadRequest

    相反,如果您的应用程序有很多层,并且错误的参数到达了您不期望的地方,您可能会抛出异常,在这些情况下,您可能会捕获并将其包装在 500 错误响应中。与 4XX 不同,您会收到 InternalServerError,因为您没有预料到它。

    【讨论】:

      猜你喜欢
      • 2012-09-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-22
      • 2012-06-08
      相关资源
      最近更新 更多