java - 如何捕获 Firebase Auth 特定异常

标签 java android exception firebase firebase-authentication

使用 Firebase,我如何捕获特定异常并优雅地告知用户?例如:

FirebaseAuthInvalidCredentialsException: The email address is badly formatted.

我正在使用下面的代码使用电子邮件和密码注册用户,但我在 java 方面并不那么先进。

mAuth.createUserWithEmailAndPassword(email, pwd)
    .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {

    @Override
    public void onComplete(@NonNull Task<AuthResult> task) {
        if (!task.isSuccessful()) {
            //H.toast(c, task.getException().getMessage());
            Log.e("Signup Error", "onCancelled", task.getException());
        } else {
            FirebaseUser user = mAuth.getCurrentUser();
            String uid = user.getUid();
        }
    }    
});

最佳答案

您可以在 try block 中抛出 task.getException 返回的异常,并捕获您正在使用的方法可能抛出的每种类型的异常。

下面是 OnCompleteListenercreateUserWithEmailAndPassword 方法的示例。

if(!task.isSuccessful()) {
    try {
        throw task.getException();
    } catch(FirebaseAuthWeakPasswordException e) {
        mTxtPassword.setError(getString(R.string.error_weak_password));
        mTxtPassword.requestFocus();
    } catch(FirebaseAuthInvalidCredentialsException e) {
        mTxtEmail.setError(getString(R.string.error_invalid_email));
        mTxtEmail.requestFocus();
    } catch(FirebaseAuthUserCollisionException e) {
        mTxtEmail.setError(getString(R.string.error_user_exists));
        mTxtEmail.requestFocus();
    } catch(Exception e) {
        Log.e(TAG, e.getMessage());
    }
}

关于java - 如何捕获 Firebase Auth 特定异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37859582/

相关文章:

java - 根据某些数组元素的状态更改按钮的颜色

java - setVisibility(View.INVISIBLE) 使我的应用程序崩溃

c# - 获取 "Index was outside the bounds of the array"异常

java - 非法三角形异常

Android服务绑定(bind)麻烦

java - 我希望 main 方法打印出值 x,该值是由正在运行的线程返回的

java - 服务器启动时违规类告诉我什么?

java - 一次在 SQLite 数据库中输入 2 条相同的记录 - Android

android - 安卓手机的蓝牙设备类别有哪些?

android - Ionic Android 应用程序无法显示透明颜色