【问题标题】:Angular $http.get: How to catch all the errors?Angular $http.get:如何捕获所有错误?
【发布时间】:2017-03-23 23:12:47
【问题描述】:

我正在向 nodejs 发送一个表单以进行身份​​验证。在以下函数中使用$http.get 并添加promise > .then。在生产中,这是否可以处理我可能从服务器获得的所有错误?我需要在这个函数中添加什么吗?

MyApp.controller("Login", function($scope, $http){

    $scope.checkuser = function(user){

        $http.get('/login', user).then(function(response){

            if(response.data){
                console.log(response.data);
                    //based on response.data create if else .. 
            } else {
                console.log("nothing returned");
            }
        });
    }
});

一如既往,非常感谢!

【问题讨论】:

  • 它不处理不成功的响应 (200)。如果是 500、401 等,那么回调将不会触发。添加 catch 块。

标签: javascript angularjs node.js angular-promise angular-http


【解决方案1】:

您的函数只处理成功的服务器响应,如 200,但它不考虑服务器异常 500 或授权错误 401 等。对于需要提供 catch 回调的那些:

$http.get('/login', user)
.then(function(response) {

    if (response.data) {
        console.log(response.data);
        //based on response.data create if else .. 
    } else {
        console.log("nothing returned");
    }
})
.catch(function() {
    // handle error
    console.log('error occurred');
})

【讨论】:

  • 所以在catch,我还需要做if(response.data=="401"){ do this}或者if(response.data=="500"){ do this}
  • catchif(response.status=="401"){ do this}; if(response.status=="500"){ do something else};AngularJS $http Service API Reference - General Usage
【解决方案2】:

我会将第二个回调添加到您的.then,这是错误处理程序。

MyApp.controller("Login", function($scope, $http){

  $scope.checkuser = function(user){

    $http.get('/login', user).then(function(response){

        if(response.data){
            console.log(response.data);
                //based on response.data create if else .. 
        } else {
            console.log("nothing returned");
        }
    }, function(error){
        //THIS IS YOUR ERROR HANDLER. DO ERROR THINGS IN HERE!
    });
  }
});

【讨论】:

    猜你喜欢
    • 2018-04-28
    • 1970-01-01
    • 2017-08-17
    • 2019-12-30
    • 2017-08-14
    • 1970-01-01
    • 2016-12-07
    • 2015-01-30
    • 1970-01-01
    相关资源
    最近更新 更多