【问题标题】:Why does this coroutine crash at run time?为什么这个协程在运行时会崩溃?
【发布时间】:2022-01-04 17:51:17
【问题描述】:

我正在尝试确保我的应用在发生后端故障时做出适当的响应,我正在使用 realm/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。

【问题讨论】:

    标签: kotlin kotlin-coroutines coroutine suspend


    【解决方案1】:

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

    【讨论】:

    • 有了你的解释和例子,现在更有意义了,谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-08
    • 2017-04-01
    • 2022-12-29
    • 2021-07-23
    相关资源
    最近更新 更多