繁体   English   中英

尝试使用 customexception 处理 firebaseauth

[英]Try to handle firebaseauth with customexception

在我的 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;
            }

        }
    });

OnFailureListener 有方法

onFailure(@NonNull Exception e)

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

    public class WrongPasswordException extends RuntimeException{
}

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM