Angular $http.get:如何捕获所有错误? [英] Angular $http.get: How to catch all the errors?

查看:34
本文介绍了Angular $http.get:如何捕获所有错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

一如既往,非常感谢!

推荐答案

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

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

这篇关于Angular $http.get:如何捕获所有错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆