首页 文章

在角度make $ http去捕获服务器响应{error:'ok'}

提问于
浏览
1
$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 .

我知道我可以从服务器更改响应头,但我想只在客户端进行 .

换句话说:

如何使用 $http promise服务,认为 200 OK 状态,在响应对象中使用"error"键,将转到 catch 而不是调用 then 函数?

3 回答

  • 1

    正如@yarons指出的那样,你可以使用一个拦截器 . 但是,你的决定是总是返回200,即使在 error 情况下,所以你为什么要在你的前端改变这种行为呢?

    Your logic seems like:

    不要告诉前端抛出错误(可能不在开发控制台中显示或现在让用户),但在内部处理它作为错误 .

    对我来说,如果你决定采取这种欺骗行为,那么就一直走下去,不要乱砍 . 只需在 then() 中查找错误消息即可 .

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

    $http.get('/data.json')
    .then(function(response){
        if(response.data.error) {
           $scope.error_message = response.data.error;
           return;
        }
    });
    
  • 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');
    
  • 1
    $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() 函数拒绝

相关问题