无法捕获Firebase异常

时间:2017-03-19 16:27:39

标签: android firebase firebase-authentication

我刚刚创建了SignIn(AppCompatActivity activity, String email, String password)方法来登录我的Firebase Android应用中的现有用户。它使用正确的凭据工作得很完美,但是当输入错误的电子邮件和/或密码时,它无法捕获正确的异常。这是方法:

public static int SignIn(final AppCompatActivity activity, String email, String password) {
    int resultTask = -2;
    FirebaseUtil.mAuth.signInWithEmailAndPassword(email, password).addOnCompleteListener(activity, new OnCompleteListener<AuthResult>() {
        @Override
        public void onComplete(@NonNull Task<AuthResult> task) {
            if (task.isSuccessful()) {
                if (!FirebaseUtil.mAuth.getCurrentUser().isEmailVerified()) {
                    FirebaseUtil.mAuth.getCurrentUser().sendEmailVerification();
                    FirebaseUtil.mAuth.signOut();
                    resultTask = 1;
                } else {
                    FirebaseUtil.isCustom = true;
                    resultTask = 2;
                }
            } else
                resultTask = -1;
        }
    });
    return resultTask;
}

输入错误的凭据时返回-2。这个方法出了什么问题?

编辑(2)

答案在这里

我通过将方法类型从int更改为void来解决了这个问题。原因如下:

在我的活动/片段中,我调用了像

这样的方法
int result = SignInUpActivity(_params_);

注意方法的默认返回值( -2 但是在执行Firebase操作后,如登录/向上,它可以返回任何其他值)。 在此行之后,我会检查result

if (result == -2) {
    // some stuff
}
else if (result == -1) {
    // some other stuff
}
else if (result == 0) {
    // ...
}
// and other value checks for result handling 

目前,我没有给Firebase提供时间来获取/检查/执行自己的身份验证方法。因此,SignInUpActivity()返回其默认值(-2)。要彻底删除头痛,我将方法类型从int更改为void

我的最终代码如下:

public static void SignIn(final AppCompatActivity activity, final String email, final String password) {
    FirebaseUtil.mAuth.signInWithEmailAndPassword(email, password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
        @Override
        public void onComplete(@NonNull Task<AuthResult> task) {
            if (!task.isSuccessful()) {
                if (task.getException() instanceof FirebaseAuthInvalidCredentialsException) {
                    /**
                     * Thrown when one or more of the credentials passed to a method fail to
                     * identify and/or authenticate the user subject of that operation.
                     * Inspect the error code and message to find out the specific cause.
                     * https://firebase.google.com/docs/reference/android/com/google/firebase/auth/FirebaseAuthInvalidCredentialsException
                     */
                    ProgressDialog.DismissProgressDialog();
                    AlertDialog.ShowAlertDialog(activity,
                            "Invalid credentials", "Check email and password again.",
                            true, "ok", null,
                            false, "", null,
                            false, -1,
                            true);
                } else if (task.getException() instanceof FirebaseAuthInvalidUserException) {
                    /**
                     * Inspect the error code and message to find out the specific cause.
                     * https://firebase.google.com/docs/reference/android/com/google/firebase/auth/FirebaseAuthInvalidUserException
                     */
                    ProgressDialog.DismissProgressDialog();
                    AlertDialog.ShowAlertDialog(activity,
                            "Invalid credentials", "Check email and password again.",
                            true, "ok", null,
                            false, "", null,
                            false, -1,
                            true);
                }
            } else {
                if (!FirebaseUtil.mAuth.getCurrentUser().isEmailVerified()) {
                    FirebaseUtil.mAuth.getCurrentUser().sendEmailVerification();
                    FirebaseUtil.mAuth.signOut();
                    ProgressDialog.DismissProgressDialog();
                    AlertDialog.ShowAlertDialog(activity,
                            "Email not verified", "To start working, please verify your email.",
                            true, "ok", null,
                            false, "", null,
                            true, R.drawable.ic_verified_user,
                            true);
                } else {
                    FirebaseUtil.isCustom = true;
                    ProgressDialog.DismissProgressDialog();
                }
            }
        }
    });
}

public static void Register(final AppCompatActivity activity, final String email, final String password) {
    FirebaseUtil.mAuth.createUserWithEmailAndPassword(email, password)
        .addOnCompleteListener(new OnCompleteListener<AuthResult>() {
            @Override
            public void onComplete(@NonNull Task<AuthResult> task) {
                if (!task.isSuccessful()) {
                    if (task.getException() instanceof FirebaseAuthUserCollisionException) {
                        /**
                         * Thrown when an operation on a FirebaseUser instance couldn't be
                         * completed due to a conflict with another existing user.
                         * https://firebase.google.com/docs/reference/android/com/google/firebase/auth/FirebaseAuthUserCollisionException
                         */
                        ProgressDialog.DismissProgressDialog();
                        AlertDialog.ShowAlertDialog(activity,
                                "Try another", "This email has already registered.",
                                true, "ok", null,
                                false, "", null,
                                false, -1,
                                true);
                    } else {
                        ProgressDialog.DismissProgressDialog();
                        AlertDialog.ShowAlertDialog(activity,
                                "Whoops", "An error occurred. Try again later.",
                                true, "ok", null,
                                false, "", null,
                                false, -1,
                                true);
                    }
                } else {
                    try {
                        FirebaseUtil.mAuth.getCurrentUser().sendEmailVerification();
                        FirebaseUtil.mAuth.signOut();
                        ProgressDialog.DismissProgressDialog();
                        AlertDialog.ShowAlertDialog(activity,
                                "The last step", "For verification, instructions sent to your email. Please, check your email.",
                                true, "ok", null,
                                false, "", null,
                                true, R.drawable.ic_verified_user,
                                true);
                    } catch (Exception e) {
                        ProgressDialog.DismissProgressDialog();
                        AlertDialog.ShowAlertDialog(activity,
                                "Whoops", "An error occurred. Try again later.",
                                true, "ok", null,
                                false, "", null,
                                false, -1,
                                true);
                    }
                }
            }
        });
}

无论如何,问题解决了。

3 个答案:

答案 0 :(得分:2)

您的方法将始终返回-2,因为您将侦听器设置为myapp.com:8000

设置一个监听器意味着当操作执行时,方法addOnCompleteListener中的代码(例如)将执行。

在你的情况下,每次调用函数onComplete时,它都会为SignIn设置一个新的监听器,这样做的正确方法是在onCreate方法中使用该函数之外的代码,每次用户尝试登录代码中的任何位置时,addOnCompleteListener方法中的代码都将被调用并执行。

请避免以这种方式写作,最好为听众创建一个新类,并将其称为onComplete,确保您需要为FirebaseUtil.mAuth.signInWithEmailAndPassword(email, password).addOnCompleteListener(new Mylistener())实现正确的界面}访问Mylistener方法

编辑:

确实要执行此登录方法,您应该这样称呼它:

onComplete

然后当上面的方法执行并完成代码中的onComplete方法时,将执行。

答案 1 :(得分:2)

根据这个问题:How to catch a Firebase Auth specific exceptions

你应该检查

if (!task.isSuccessful())

但你正在做

if (task.isSuccessful())

然后你可以在try块中抛出task.getException返回的Exception,并捕获你正在使用的方法可能抛出的每种类型的Exception

答案 2 :(得分:0)

您没有收到任何异常,因为您没有在onComplete()中捕获异常。 阅读此代码供您参考。       这里是mAuth = FirebaseAuth.getInstance();

   mAuth.signInWithEmailAndPassword(email,password).addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                @Override
                public void onComplete(@NonNull Task<AuthResult> task) {
                // If task is successful write method which you wan to do .
                 Log.d(LOG_TAG, "signIn With Email:onComplete");

                    // If signin 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 is unsuccessful then catch exception
                 // following are the possible exception which can  occurs  in signInWithEmailAndPassword(). 

                     if (!task.isSuccessful()) {

                        try {
                            throw task.getException();
                        } catch (FirebaseAuthInvalidUserException e) {
                            //  show error toast to user or do something
                        } catch (FirebaseAuthInvalidCredentialsException e)  {
                        //  show error toast to user or do something

                        } catch (FirebaseNetworkException e) {
                            //  show error toast to user or do something

                        } catch (Exception e) {
                            Log.e(LOG_TAG, e.getMessage());
                        }
                        Log.w(LOG_TAG, "signInWithEmail:failed",task.getException());
                    }

                }
            });
相关问题