简体   繁体   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')})

The server response is: 服务器响应是:

200 OK
content-type: application/json

{error:'cannot get the data'}

I want that the response will go to the .catch not to .then . 我想,响应会去.catch不要.then

I know that I can change the response header from the server, but I want to do it only on the client side. 我知道我可以从服务器更改响应头,但我想只在客户端进行。

In other Words: 换一种说法:

How I make angular $http promise service, to think that 200 OK status, with "error" key in the response object, will go to catch instead of invoking the then function? 我如何制作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')
})

Just as others suggested, you can check for the conditions you want the request to be treated as a failure inside the .then block and reject using angular $q service reject() function 正如其他人建议的那样,您可以检查您希望在.then块中将请求视为失败的条件.then并使用angular $q service reject()函数reject()

You can use an 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');

As @yarons pointed out, you could use an interceptor. 正如@yarons指出的那样,你可以使用一个拦截器。 But, your decision was to always return 200, even in an error case, so why do you want to change this behaviour in your Front End now? 但是,即使在error情况下,您的决定总是返回200,那么为什么要在前端更改此行为呢?

Your logic seems like: 你的逻辑似乎是:

Don't tell the front end to throw an error (maybe to not show in the dev console or let the user now), but handle it internally as an error. 不要告诉前端抛出错误(可能不在开发控制台中显示或让用户现在),但在内部处理它作为错误。

For me, if you decide to go for this trick-behaviour, go all the way and don't hack something around. 对我来说,如果你决定采取这种欺骗行为,那么就一直走下去,不要乱砍。 Just look in the then() for the error message. 只需在then()查找错误消息即可。

So go in the then() , as you planned, and then catch your error there with an if clause: 所以按照你的计划进入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