0

我正在使用Firebase,我正在使用一种方法为用户创建一个名为“createUserWithEmailAndPassword”的帐户。如何覆盖createUserWithEmailAndPassword方法的异常?

我在Firebase references中发现此方法异常之一是“FirebaseAuthWeakPasswordException”,它在密码少于6个字符时调用。

我想赶上这个例外,并显示用户的消息与我自己的话, 但是当我缠上尝试&捕捉的方法我得到这个错误:“异常“com.google.firebase.auth.FirebaseAuthWeakPasswordException '永远不会出现在相应的尝试块“中。 我试图解决这一段时间,但没有运气。 这里是代码的片段,希望你能帮助我想出解决办法:

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

       @Override 
       public void onComplete(@NonNull Task<AuthResult> task) { 
        // Log.d(TAG, "createUserWithEmail:onComplete:" + task.isSuccessful()); 

        // If sign in fails, display a message to the user. If sign in succeeds 
        // the auth state listener will be notified and logic to handle the 
        // signed in user can be handled in the listener. 

        if(task.isSuccessful()) 
        { 
         Toast.makeText(getApplicationContext(),"Account has created!",Toast.LENGTH_SHORT).show(); 
        } 
        if (!task.isSuccessful()) { 
         Toast.makeText(getApplicationContext(), "failed!", 
           Toast.LENGTH_SHORT).show(); 
        } 
       } 

      }); 

回答

1

您还没有加,这就是为什么你不能得到正确的错误代码或异常FailureListener的。

将它添加到毛特这样

mAuth.createUserWithEmailAndPassword(email, pass) 
     .addOnFailureListener(this, new OnFailureListener() { 
        @Override 
        public void onFailure(@NonNull Exception e) { 
         if (e instanceof FirebaseAuthException) { 
          ((FirebaseAuthException) e).getErrorCode()); 
          //your other logic goes here 
         } 
        } 
       }) 

不要让我知道,如果它改变了你什么。

+0

太谢谢你了! 它现在正在工作,我只是将“e instanceof”更改为每个可能的异常,完全像我的问题中的参考链接: FirebaseAuthWeakPasswordException,FirebaseAuthInvalidCredentialsException和FirebaseAuthUserCollisionException。 – zb22

+0

很高兴它:)。祝你好运。 –

1

你需要调用task.getException()然后用instanceof

mAuth.createUserWithEmailAndPassword("[email protected]", "only5") 
    .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() { 
     @Override 
     public void onComplete(@NonNull Task<AuthResult> task) { 
      Log.i(TAG, "createUserWithEmail:onComplete:" + task.isSuccessful()); 

      if (!task.isSuccessful()) { 
       Log.w(TAG, "onComplete: Failed=" + task.getException().getMessage()); 
       if (task.getException() instanceof FirebaseAuthWeakPasswordException) { 
        Toast.makeText(MainActivity.this, "Weak Password", Toast.LENGTH_SHORT).show(); 
       } 
      } 
     } 
    }); 
+0

我也很感谢你的方法。对我很有帮助。 –

+0

是的,这是解决它的另一个好方法,谢谢。 在发布之前,我也尝试过“task.getException()。getMessage()”,这给出了内置的错误消息,使用“instanceof”的方式并未跨越我的想法。 – zb22