尝试/ catch块不处理发生的错误

时间:2015-01-29 17:30:56

标签: javascript angularjs try-catch angularfire

这个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.')
}

1 个答案:

答案 0 :(得分:0)

查看$authWithPassword方法的source code here。正如您可以看到是否会抛出错误 - firebase将返回被拒绝的承诺。所以你可以在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);
});