Kotlin协程,如何在协程中捕获异常

时间:2019-07-11 14:03:56

标签: exception retrofit2 kotlin-coroutines

在coroutineScope块中的

调用retotrfit(在最新版本中,它具有coroutines支持)。但是,当远程URL错误时,即使将其包装在try / catch中,也不会捕获到异常。

suspend fun fetchData() {
val service = ServiceFactory().createRetrofitService(RemoteDataServiice::class.java, baseUrl+"http:\\fake.url.com\", httpClient)

coroutineScope {
    try {
        val response = service.getRemoteData(path, headers, params)
        try {
            val headerList = response.headers()
            val success = response.isSuccessful
            val code = response.code() // http status code
            var message = response.message() // HTTP status message

            // ……
            processResponse(response.body(), success, code, message, headerList)


        } finally {

            response.body()?.close()
        }
    } catch (t: Throwable) {

        withContext(Dispatchers.Default) {
            processResponse(null, false, -1, t.message, null)
        }
    }
}
   //...... do something after the coroutineScope is complete
}

未捕获到异常并崩溃。如何在coroutineScope {}中捕获异常?

另一个问题,不要认为我需要将withContext(Dispatchers.Default)放在catch的情况下,因为它仍然在coroutineScope{}中,对吗?

0 个答案:

没有答案