【发布时间】:2022-01-16 20:36:10
【问题描述】:
我正在使用 okHttp 加载数据。
加载数据时发生RuntimeException,导致okhttpDispatcher崩溃。
我使用协程,但它们没有捕获异常并且应用程序崩溃。
如何正确捕获拦截器中抛出的异常?
注意:如果出现IOException,这个构造会正常执行。
class CommentsViewModel(val api: IRetrofitApi): ViewModel(){
fun getComments(){
viewModelScope.launch(exceptionHandler) {
api.loadComments() //When RuntimeException this didn`t catch
}
}
val exceptionHandler = CoroutineExceptionHandler { _, throwable ->
showError(throwable)
}
}
interface IRetrofitApi {
@GET("/comments")
suspend fun loadComments() : CommentList
}
class NetworkModule{
fun getClient(): OkHttpClient {
return OkHttpClient.Builder()
.addInterceptor{ chain ->
val request = chain.request().newBuilder()
chain.proceed(request.build())
throw RuntimeException()
}.build()
}
}
【问题讨论】:
标签: kotlin okhttp kotlin-coroutines