Crash OkHttp dispatcher when use kotlin-coroutine

Viewed 512

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

    }
}
1 Answers

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.

Related