繁体   English   中英

使用 kotlin-coroutine 时 OkHttp 调度程序崩溃

[英]Crash OkHttp dispatcher when use kotlin-coroutine

我正在使用 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()

    }
}

https://stackoverflow.com/a/58711127/1542667

您不应该从拦截器中抛出 RuntimeException,它被视为无法干净处理的致命错误。 OkHttp 偶尔会包装来自底层库(如 Android 网络)的特定 RuntimeExceptions,但否则您应该使用 IOException。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM