简体   繁体   English

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

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

This try catch block doesn't seem to catch the error that occurs, which is strange, considering I have a similar try catch block for the registration part of the site. 考虑到我的站点注册部分也有类似的try catch块,因此该try catch块似乎无法捕获所发生的错误,这很奇怪。 This handles the login. 这处理登录。 The error occurs at the third line email: $scope.authInfo.email and throws this error: 该错误发生在第三行email: $scope.authInfo.email并引发以下错误:

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

This occurs when the email format is wrong, for example test@ . 当电子邮件格式错误时会发生这种情况,例如test@ So when it is I want an error message to be set in the catch block. 因此,当我希望在catch块中设置错误消息时。

Does anyone know why this try catch isn't working? 有谁知道为什么这个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.')
}

Look at the source code here of $authWithPassword method. 这里查看 $authWithPassword方法的源代码 As you can see if error will be thrown - firebase will return rejected promise. 如您所见,是否会引发错误-Firebase将返回被拒绝的Promise。 So you can handle your error in the promise catch block: 因此,您可以在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