Home > Mobile >  Cannot handle exception in firebase function
Cannot handle exception in firebase function

Time:03-13

i'm trying to understand with no luck why this throwable is not catched in my catch block:

CoroutineScope(IO).launch {
        try {   FirebaseMessaging.getInstance().token.addOnCompleteListener(OnCompleteListener { task ->
                if (task.isSuccessful) {
                    token = task.result
                }
                throw Exception("Hi There!")
            }).await()
            getUsers().await()
        }catch (e: Exception){
           binding.txtTitle.text = "Error: ${e.message}"
        }
    }

The exception is called but the app crash and not handle by the catch block. But if i throw an exception outside the addOnCompleteListener the exception is handled normally. My objective is to stop the execution of the getUsers function if no token is available.

CodePudding user response:

The exception which is thrown in OnCompleteListener will not propagate to the outer scope, it is scoped to OnCompleteListener block. To achieve your objective I would recommend to rewrite the code to something like the following:

coroutineScope.launch {
    try {
        val token: String = FirebaseMessaging.getInstance().token.await()
        if (token.isNotEmpty) {
            getUsers().await()
        }
    } catch (e: Exception){
        // ...
    }
}

await function waits for task to complete.

  • Related