【问题标题】:Try to handle firebaseauth with customexception尝试使用自定义异常处理 firebase 身份验证
【发布时间】:2020-09-03 09:27:15
【问题描述】:

在我的 android 项目中,我尝试在 FirebaseAuth reauthenticate.onFailure 块中引发自定义异常,以处理用户输入的错误密码。但它不起作用。 IDE 说我应该将 throw 语句放在 try 和 catch 块中,但它也不起作用。请有人告诉我这是否可能以某种方式实现?

 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;
            }

        }
    });

【问题讨论】:

    标签: java exception firebase-authentication


    【解决方案1】:

    OnFailureListener 有方法

    onFailure(@NonNull Exception e)
    

    并且您需要重写此特定方法以提供您的实现。但是,您不能从此方法中抛出异常,因为方法签名中没有 throws。 因此,您将无法从该方法实现中抛出已检查异常,但是没有人可以阻止您从该方法中抛出 RuntimeException,因为它们不是已检查异常。所以如果它适合你的场景,你可以做这样的事情。

        public class WrongPasswordException extends RuntimeException{
    }
    

    随意编辑或评论,因为它可能对其他人有所帮助。

    【讨论】:

      猜你喜欢
      • 2011-09-17
      • 2020-04-01
      • 2022-12-10
      • 2016-03-25
      • 2019-09-18
      • 1970-01-01
      • 2013-03-28
      • 2019-09-30
      相关资源
      最近更新 更多