簡體   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