【问题标题】:Try/catch block not handling the error that occursTry/catch 块不处理发生的错误
【发布时间】:2015-01-29 17:30:55
【问题描述】:

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

【问题讨论】:

    标签: javascript angularjs try-catch angularfire


    【解决方案1】:

    source code here$authWithPassword方法。如您所见,是否会引发错误 - 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);
    });
    

    【讨论】:

    • 正确的答案是删除最后一个 .catch 并将开关放在第一个 catch 中。除此之外它有效。你知道为什么我必须把 .catch 放在 then 之前吗?在 Firebase 的网站上,他们使用 .then before。
    • @Chrillewoodz 是的,你是对的。事实是我没有完全阅读你的问题。只是看到了原因或你的麻烦,并在同一时间回答。对不起。
    • @Chrillewoodz 但请记住 - 您必须在 catch block 中抛出错误。如果您不这样做 - 将处理错误,并调用 then block
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多