sonrohancue
sonrohancue

Reputation: 341

Why does this coroutine crash at run time?

I am trying to make sure my app responds appropriate in the event of a backend failure, I am using realm/mongo to create an async task that fetches the user.

I have these two blocks:

override suspend fun logIn(accessToken: String) {
        val user = logInInternal(accessToken)
        realmAsyncOpen(user)
    }

and

private suspend fun logInInternal(accessToken: String) = suspendCancellableCoroutine<User> { continuation ->
        val customJWTCredentials: Credentials = Credentials.jwt(accessToken)
        app.loginAsync(customJWTCredentials) {
            if (it.isSuccess) {
                continuation.resumeWith(Result.success(app.currentUser()!!))
            } else {
                continuation.resumeWithException(RealmLoginException().initCause(it.error))
            }
        }
    }

logInInternal crashes when I hit the resumeWithException part. I have also tried using app.login(credentials) since the method is suspending, without luck there. Why does my app crash when I resume with exception?

I am causing the call to 502 out when hit.

Upvotes: 1

Views: 811

Answers (1)

Sergio
Sergio

Reputation: 30645

The docs of resumeWithException say:

Resumes the execution of the corresponding coroutine so that the exception is re-thrown right after the last suspension point.

Which means you need to catch that exception:

override suspend fun logIn(accessToken: String) {
    try {
        val user = logInInternal(accessToken)
        realmAsyncOpen(user)
    } catch(e: RealmLoginException /*or e: Exception - to catch all exceptions*/) {
        // handle exception
    } 
}

Upvotes: 1

Related Questions