簡體   English   中英

為什么這個協程在運行時會崩潰?

[英]Why does this coroutine crash at run time?

我試圖確保我的應用程序在后端失敗的情況下做出適當的響應,我正在使用領域/mongo 創建一個獲取用戶的異步任務。

我有這兩個塊:

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

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))
            }
        }
    }

當我點擊resumeWithException部分時, logInInternal崩潰。 我也嘗試過使用 app.login(credentials) ,因為該方法正在暫停,但沒有運氣。 為什么我的應用程序在異常恢復時會崩潰?

我在被擊中時導致撥打 502。

resumeWithException的文檔說:

恢復相應協程的執行,以便在最后一個暫停點之后立即重新拋出異常。

這意味着您需要捕獲該異常:

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
    } 
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM