【问题标题】:In angular make $http go to catch if server response with {error:'ok'}如果服务器响应带有 {error:'ok'}
【发布时间】:2015-11-23 20:18:38
【问题描述】:
$http.get('/data.json')
.then(function(){console.log('ok'})
.catch(function(){console.log('no ok')})

服务器响应是:

200 OK
content-type: application/json

{error:'cannot get the data'}

我希望回复到.catch 而不是.then

我知道我可以从服务器更改响应标头,但我只想在客户端这样做。

换句话说:

我如何制作 Angular $http 承诺服务,认为 200 OK 状态,在响应对象中带有“错误”键,将转到 catch 而不是调用 then功能?

【问题讨论】:

  • 你试过使用'throw'吗?
  • 你不能在then处理程序中分支吗?
  • 'catch' 只是 'then' 函数的简写,因此 promise 显然永远不会转到 'then' 函数,并且由于 promise 已被处理,它永远不会转到 'catch'。此外,您在 then 函数中缺少响应对象
  • 有点迂腐,扩展@Indrajith 的评论。 Catch 是 then(null, function(response) { alert('error catch') }) 的简写。所以它只实现了 then 函数中的第二个参数。

标签: javascript angularjs


【解决方案1】:

您可以使用interceptor

yourApp.factory('myInterceptor', ['$q', function($q) {
  return {
    response: function(response) {
      if (response.status === 200 && response.data.error) {
        return $q.reject(response);
      }
      else {
        return response;
      }
    }
  };
}]);

$httpProvider.interceptors.push('myInterceptor');

【讨论】:

  • 谢谢。这就是我所寻找的。不更改所有源代码的最优雅方式。
【解决方案2】:
$http.get('/data.json')
.then(function(res){
   if(res.error === 'cannot get the data'){
     return $q.reject(res)
   }
   return res;
)
.then(function(){console.log('ok'})
.catch(function(){
   console.log('no ok')
})

正如其他人建议的那样,您可以在 .then 块内检查您希望将请求视为失败的条件,并使用 angular $q service reject() 函数拒绝

【讨论】:

  • 你的一个代码路径返回一个承诺,另一个没有。这是不可链接的。
  • @SergioTulentsev AFAIK 在 then() 块中返回一个值,将其包装成一个承诺。但他可以使用$q.when() 明确地包装后面的部分
【解决方案3】:

正如@yarons 指出的那样,您可以使用拦截器。但是,您的决定是始终返回 200,即使在 error 情况下也是如此,那么为什么您现在要在前端更改此行为呢?

你的逻辑是这样的:

不要告诉前端抛出错误(可能不会显示在 开发控制台或让用户现在),但在内部将其作为 错误。

对我来说,如果你决定采用这种技巧行为,那就一路走下去,不要乱砍乱砍。只需在 then() 中查找错误消息即可。

所以按照您的计划进入then(),然后使用if 子句捕获您的错误:

$http.get('/data.json')
.then(function(response){
    if(response.data.error) {
       $scope.error_message = response.data.error;
       return;
    }
});

【讨论】:

    猜你喜欢
    • 2016-04-09
    • 1970-01-01
    • 1970-01-01
    • 2020-07-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-31
    • 1970-01-01
    相关资源
    最近更新 更多