2016-09-18 107 views
1

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

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

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

+1

你在使用什么库?不应该是').error(function()...)'? – Barmar

+0

@Barmar“...然后(...)。错误不是函数”这是我现在得到的错误 –

+0

这是什么库?这不是jQuery。它是否是角度? – Barmar

回答

0

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

return { 
     'responseError': function(config) { 

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

       return config; 
      } 

      return config; 
     } 
    } 

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

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 
    }); 
+0

500内部服务器错误仍然在第一个功能 –

+0

您的REST api返回状态为500?你有任何处理Ajax呼叫的角度拦截器吗? – Developer

+0

是的。现在解决了问题。 –

1

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

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

你想两个功能作为你的参数然后()。第一个是你的successCallback,第二个是你的errorCallback。

作为替代方案,您可以在您的承诺链中添加一个catch()。这更容易阅读和防止类似你的错误。