Javascript http获取成功函数捕获错误响应

时间:2016-09-18 09:38:47

标签: javascript angularjs http

我正在向一个正在回复500 error响应的网址发出http请求(这是预期的行为)。但是这个错误是在成功函数中捕获而不是错误函数。

$http.get("myUrl")
    .then(function (response) {
        console.log(response);
    }
    .function (error) {
        // Handle error here
    });

请帮助理解这一点以及使用它的正确方法。

3 个答案:

答案 0 :(得分:1)

应该是:

$http.get("myUrl")
    .then(function (response) {
        console.log(response);
    }
    ,function (error) {
        // Handle error here
    });

或者

$http.get("myUrl")
    .then(function (response) {
        console.log(response);
    })
    .catch (function(error) {
        // Handle error here
    });

答案 1 :(得分:1)

如果这是angulars $ http,它应该是这样的:

$http.get("myUrl")
  .then(
    function (response) {
      console.log(response);
    },
    function (error) {
      // Handle error here
    }
  );

你想要两个函数作为then()的参数。第一个是你的successCallback,第二个是你的errorCallback。

作为替代方案,您可以在promise链中添加catch()。这更容易阅读,并防止像你这样的错误。

答案 2 :(得分:0)

我的应用程序中有一个拦截器导致问题。 我的所有错误响应都被拦截并返回,没有状态。以下是代码。

return {
        'responseError': function(config) {

            if(config.status===401){
              //Do Something

              return config;
            }

          return config;
        }
    }

将return语句更改为return $q.reject(config);开始返回正确的状态。