使用 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
返回的异常,并捕获您正在使用的方法可能抛出的每种类型的异常。
下面是 OnCompleteListener
中 createUserWithEmailAndPassword
方法的示例。
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/