Oh Pie
Oh Pie

Reputation: 23

Try to handle firebaseauth with customexception

in my android project I try to throw a custom exception in the FirebaseAuth reauthenticate.onFailure block to handle wrong password input from user. But it doesn't work. The IDE says I should put the throw statement in a try and catch block, but it doesn't work either. Please can someone tell me if this is even possible or not in some way?

 public void verifyUserPassword(String password) throws WrongPasswordException {
    AuthCredential credential = EmailAuthProvider.getCredential(user.getEmail(), password);

    user.reauthenticate(credential).addOnFailureListener(new OnFailureListener() {
        @Override
        public void onFailure(@NonNull Exception e) {
            String errorCode = ((FirebaseAuthException) e).getErrorCode();

            if (errorCode.equals("ERROR_WRONG_PASSWORD")) {
                    throw new WrongPasswordException("Wrong password");
            }

        }
    });

}



btnConfirm.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            String password = etPassword.getText().toString().trim();

            if (TextUtils.isEmpty(password)) {
                Toast.makeText(getContext(), "Field can not be empty", Toast.LENGTH_SHORT).show();
                return;
            }

            try {
                accountListener.verifyUserPassword(etPassword.getText().toString());
                profileChangeListener.onProfileAddOpen();
                getDialog().dismiss();
            } catch (WrongPasswordException e) {
                Toast.makeText(getContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
                return;
            }

        }
    });

Upvotes: 1

Views: 55

Answers (1)

Tushar Jajodia
Tushar Jajodia

Reputation: 451

OnFailureListener has method

onFailure(@NonNull Exception e)

And you need to override this particular method to provide your implementation. However you are not allowed to throw Exceptions from this method because there is no throws in the method signature. So You will not be able to throw Checked Exceptions from within this method implementation however no one can stop you from throwing RuntimeException from this method as they are not checked Exceptions. So You can do something like this if it fits your scenarios.

    public class WrongPasswordException extends RuntimeException{
}

Feel free to edit or comment as it may help someone else.

Upvotes: 1

Related Questions