【问题标题】:Crash OkHttp dispatcher when use kotlin-coroutine使用 kotlin-coroutine 时 OkHttp 调度程序崩溃
【发布时间】: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


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2020-02-10
    • 2018-04-03
    • 2017-01-12
    • 1970-01-01
    • 2021-04-21
    • 2023-03-25
    • 2016-03-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多