简体   繁体   中英

Crash OkHttp dispatcher when use kotlin-coroutine

I am loading data using okHttp.

RuntimeException occurs while loading data, causing the okhttpDispatcher to crash.

I use coroutines, but they do not catch the exception and the application crashes.

How to properly catch the exception thrown in the interceptor?

Note: In case of an IOException, this construction will be executed normally.

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()

    }
}

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

You should not throw RuntimeException from an interceptor, it's treated as a fatal error that isn't possible to handle cleanly. OkHttp very occasionally wraps specific RuntimeExceptions from underlying libraries like Android networking, but otherwise you are expected to use IOException.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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