Kotlin 中的协程已经成为在网络请求中比较常用的一种方式,除了正常请求外,我们同样需要处理请求中的异常情况,本篇文章将处理协程中的异常分为以下几个部分:
一、try-catch
1.1 try-catch基础使用
1.2 什么情况下try-catch会无效?
1.3 什么是协程的结构化并发?
二、CoroutineExceptionHandler
2.1 CoroutineExceptionHandler的介绍
2.2 CoroutineExceptionHandler的使用
2.3 CoroutineExceptionHandler的不足
三、SupervisorScope+async
四、结论
一、try-catch捕获异常
1.1 try-catch基础使用
一般来说,处理异常可以使用try-catch块,在try中编写请求代码,catch负责捕获异常。
以一个普通的请求为例:
Api接口:
interface ProjectApi {
@GET("project/tree/json")
suspend fun loadProjectTree(): BaseResp<List<ProjectTree>>
@GET("project/tree/jsonError")
suspend fun loadProjectTreeError(): BaseResp<List<ProjectTree>>
}
Api接口里面列出了两个接口,一个loadProjectTree()作为能够请求成功的接口,loadProjectTreeError()则故意在path中多加了’Error’,模拟请求失败的状态。
具体调用:
suspend fun loadProjectTree() {
try {
val result = service.loadProjectTree()
val errorResult = service.loadProjectTreeError()
Log.d(TAG, "loadProjectTree: $result")
Log.d(TAG, "loadProjectTree errorResult: $errorResult")
} catch (e: Exception) {
Log.d(TAG, "loadProjectTree: Exception " + e.message)
e.printStackTrace()
}
}
我们看调用后的结果:
loadProjectTree: Exception HTTP 404 Not Found