Try/catch 块不处理发生的错误

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方法的source code here。如您所见,是否会抛出错误 - firebase 将 return 拒绝承诺。所以你可以在 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);
});