Home > database >  do I need to use try and catch in Firebase authentication codes in Kotlin - Android
do I need to use try and catch in Firebase authentication codes in Kotlin - Android

Time:02-17

Do I need to use try and catch in Firebase authentication codes in Kotlin? i.e. in here or similar places you know as experts the goal is to prevent the crashes:

fun handleFirebaseAuthWithGoogle(idToken: String) {
    val credential = GoogleAuthProvider.getCredential(idToken, null)
    FirebaseAuthRepository().auth.signInWithCredential(credential)
        .addOnCompleteListener { task ->
            if (task.isSuccessful) {
                _isNewUser.value = task.result.additionalUserInfo?.isNewUser
                // Sign in success, update UI with the signed-in user's information
                Log.d(LoginFragment.TAG, "signInWithCredential:success")
                FirebaseAuthRepository().getCurrentUser {
                    _authWithGoogle.value = it
                }
            } else {
                // If sign in fails, display a message to the user.
                Log.w(LoginFragment.TAG, "signInWithCredential:failure", task.exception)
            }
        }
}

also here:

override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
    super.onActivityResult(requestCode, resultCode, data)
    // Result returned from launching the Intent from GoogleSignInApi.getSignInIntent(...);
    if (requestCode == RC_SIGN_IN) {
        val task = GoogleSignIn.getSignedInAccountFromIntent(data)
        try {
            // Google Sign In was successful, authenticate with Firebase
            val account = task.getResult(ApiException::class.java)!!
            Log.d(TAG, "firebaseAuthWithGoogle:"   account.id)
            viewModel.handleFirebaseAuthWithGoogle(account.idToken!!)
            UiUtils.showSnackBar(requireView(), "Google sign in Succeed", 0)
        } catch (e: ApiException) {
            // Google Sign In failed, update UI appropriately
            Log.w(TAG, "Google sign in failed", e)
            hideProgress()
            UiUtils.showErrorSnackBar(requireView(), "Google sign in failed", 0)
        }
    }
}

CodePudding user response:

When you are attempting to implement an authentication mechanism, there are multiple operations that can go wrong. In such cases, we always need to handle the Exceptions.

In your second snippet code, it makes sense to use a try-catch to handle the ApiException, while in the first it doesn't. When you deal with Firebase services, you can get a successful operation or an Exception, never both. It's one or the other. So if the task is successful, then you are successfully authenticated, otherwise, you get an Exception. You can get the corresponding Exception by calling getException() method on the Task object. So there is no need to use a try-catch here because your app won't crash in case of an Exception.

CodePudding user response:

You can use .addOnSuccessListener and .addOnFailureListener to handle the different FirebaseExceptions which can be thrown while authentication.

  • Related