首页 > 解决方案 > Kotlin协程异常处理——如何抽象try-catch

问题描述

我试图了解 Kotlin 协程中的异常处理,所以我想出了这个非常简单的场景,其中网络调用引发异常,我的应用程序必须捕获并处理它。

如果我用 try-catch 块包围我的 async.await() 调用,它会按预期工作。但是,如果我尝试将 try-catch 抽象为扩展函数,我的应用程序就会崩溃。

我在这里想念什么?

import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import kotlinx.coroutines.*

class Main2Activity : AppCompatActivity() {

    private val job: Job = Job()
    private val scope = CoroutineScope(Dispatchers.Default + job)

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main2)
        runCode()
    }

    private suspend fun asyncCallThrowsException(): Deferred<Boolean> =
        withContext(Dispatchers.IO) {
            Thread.sleep(3000)// simulates a blocking request/response (not on the Main thread, though)
            throw(Exception())
        }

    suspend fun <T> Deferred<T>.awaitAndCatch() {
        try {
            this.await()
        } catch (e: Exception) {
            println("exception caught inside awaitAndCatch")
        }
    }

    private fun runCode() {
        scope.launch {

            //This block catches the exception.
            try {
                val resultDeferred = asyncCallThrowsException()
                resultDeferred.await()
            } catch (e: Exception) {
                println("exception caught inside try-catch")
            }

            //This line does not, and crashes my app.
            asyncCallThrowsException().awaitAndCatch()
        }
    }
}

编辑:我实际上忘记将调用包装在一个async块内。现在,即使是显式的 try-catch 块也不起作用......

import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import kotlinx.coroutines.*

class Main4Activity : AppCompatActivity() {

    private val job: Job = Job()
    private val scope = CoroutineScope(Dispatchers.Default + job)

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        runCode()
    }

    private suspend fun callThrowsException(): String =
        withContext(Dispatchers.IO) {
            Thread.sleep(3000)// simulates a blocking request/response (not on the Main thread, though)
            throw(Exception())
            "my result"
        }

    suspend fun <T> Deferred<T>.awaitAndCatch(): T? {
        try {
            return this.await()
        } catch (e: Exception) {
            println("exception caught inside awaitAndCatch")
        }
        return null
    }

    private fun runCode() {
        scope.launch {

            val resultDeferred: Deferred<String> = async { callThrowsException() }
            var result: String?

//            This doesn't catch the throwable, and my app crashes - but the message gets printed to the console.
            try {
                result = resultDeferred.await()
            } catch (e: Exception) {
                println("exception caught inside try-catch")
            }

//            This doesn't catch the throwable, and my app crashes - but the message gets printed to the console.
            result = resultDeferred.awaitAndCatch()
        }
    }
}

标签: exceptionkotlinkotlin-coroutines

解决方案


问题与您如何捕获异常无关。问题是,当您的异步作业失败(抛出异常)时,它会取消您为活动所做的作业。

即使您的代码可以捕获异常并打印消息,父作业也会尽快终止。

而不是像这样:val: Job = Job(),尝试val: Job = SupervisorJob()

当其子项失败时,主管作业不会被取消,因此这不会使您的应用程序崩溃。

或者,如果您想要一种方法来启动没有此问题的异步作业,请参阅:Safe async in a given scope


推荐阅读