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

查看:62
本文介绍了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天全站免登陆