繁体   English   中英

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

[英]In angular make $http go to catch if server response with {error:'ok'}

$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 promise服务,认为200 OK状态,在响应对象中带有“error”键,是否会catch而不是调用then函数?

$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块中将请求视为失败的条件.then并使用angular $q service reject()函数reject()

你可以使用一个拦截器

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');

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

你的逻辑似乎是:

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

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM