繁体   English   中英

尝试/捕获块无法处理发生的错误

[英]Try/catch block not handling the error that occurs

考虑到我的站点注册部分也有类似的try catch块,因此该try catch块似乎无法捕获所发生的错误,这很奇怪。 这处理登录。 该错误发生在第三行email: $scope.authInfo.email并引发以下错误:

Error: Firebase.authWithPassword failed: First argument must contain the key "email" with type "string"

当电子邮件格式错误时会发生这种情况,例如test@ 因此,当我希望在catch块中设置错误消息时。

有谁知道为什么这个try catch失败了?

try {
    $scope.syncAuth.$authWithPassword({
        email: $scope.authInfo.email,
        password: $scope.authInfo.password
    }).then(function(authData) {
        $scope.isSuccessful = true;
        $scope.success = 'You have successfully logged in - Redirecting...';
        $rootScope.loggedIn = true;
        $timeout($scope.redirectUser, 3000);
    }).catch(function(error) {

        switch (error.code) {

            case 'INVALID_USER': $scope.errors.push('The email you have entered is not a registered user.'); 
                                break;

            case 'INVALID_PASSWORD': $scope.errors.push('Invalid password.'); 
                                break;
        }
    });
}
catch (err) {
    $scope.errors.push('Invalid email format.')
}

这里查看 $authWithPassword方法的源代码 如您所见,是否会引发错误-Firebase将返回被拒绝的Promise。 因此,您可以在promise catch块中处理错误:

$scope.syncAuth.$authWithPassword({
    email: $scope.authInfo.email,
    password: $scope.authInfo.password
})
.catch(function(error) {
    switch (error.code) {
        case 'INVALID_USER': 
            $scope.errors.push('The email you have entered is not a registered user.');
            break;
        case 'INVALID_PASSWORD': 
            $scope.errors.push('Invalid password.');
            break;
        default:
            $scope.errors.push('Invalid email format.')
    }
    throw error;
})
.then(function(authData) {
    $scope.isSuccessful = true;
    $scope.success = 'You have successfully logged in - Redirecting...';
    $rootScope.loggedIn = true;
    $timeout($scope.redirectUser, 3000);
});

暂无
暂无

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

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