Angular $http.get: How to catch all the errors?

爱⌒轻易说出口 提交于 2019-12-10 10:22:28

问题


Im sending a form to nodejs for authentication. Using $http.get in the following function and adding a promise > .then. In production, does this handle all the errors that I may get from the server? Do I need to add anything else to this function?

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");
            }
        });
    }
});

As always, many thanks!


回答1:


Your function only handles successful server responses like 200, but it doesn't account for server exceptions 500 or authorized errors 401, etc. For those you need to provide catch callback:

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



回答2:


I would add the second callback to your .then, which is the error handler.

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!
    });
  }
});


来源:https://stackoverflow.com/questions/42988661/angular-http-get-how-to-catch-all-the-errors

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!