繁体   English   中英

Angular $ http.get:如何捕获所有错误?

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

我发送一个表单到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回调:

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

我会将第二个回调添加到你的.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!
    });
  }
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM