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