处理Kotlin Coroutines中的自定义okhttp拦截器引发的异常 [英] Handle exceptions thrown by a custom okhttp Interceptor in Kotlin Coroutines
问题描述
我在Android应用程序中使用了自定义Interceptor
以及Retrofit客户端,这在某些特定情况下会引发Exception.我正在尝试使用Kotlin协程使其正常工作.
I'm using a custom Interceptor
along with Retrofit client in my Android app, that throws an Exception under some specific circumstances. I'm trying to make it work using Kotlin coroutines.
问题是我无法处理前面提到的错误,因为从Interceptor实例中引发异常的那一刻起,它使整个应用程序崩溃,而不是被协程的try/catch
语句捕获.当我使用Rx实现时,异常被完美地传播到了onError
回调中,在这里我能够以所需的方式对其进行处理.
The problem is that I'm unable to handle the before mentioned error, since in the moment the exception is thrown from within the Interceptor instance, it crashes the whole app instead of being caught in the coroutine's try/catch
statement. While I was using the Rx implementation, the exception was flawlessly propagated to the onError
callback where I was able to handle it the way I needed.
我想这与网络调用所使用的基础线程有某种关系,请在引发异常之前从调用发生的地方,拦截器以及堆栈跟踪中查看以下日志,以及stacktrace:
I guess this is somehow related to the underlying threads that are being used for the network call, please see the logs below from the place where the call is made, from the interceptor just before throwing the exception, and the stacktrace:
2019-11-04 17:17:34.515 29549-29729/com.app W/TAG: Running thread: DefaultDispatcher-worker-1
2019-11-04 17:17:45.911 29549-29834/com.app W/TAG: Interceptor thread: OkHttp https://some.endpoint.com/...
2019-11-04 17:17:45.917 29549-29834/com.app E/AndroidRuntime: FATAL EXCEPTION: OkHttp Dispatcher
Process: com.app, PID: 29549
com.app.IllegalStateException: Passed refresh token can\'t be used for refreshing the token.
at com.app.net.AuthInterceptor.intercept(AuthInterceptor.kt:33)
我应该怎么做才能正确地从拦截器捕获并处理此异常?我想念什么吗?
What am I supposed to do in order to be able to catch and handle this exception from the Interceptor correctly? Am I missing something?
推荐答案
您应该将IOException
子类化,并使用它来将信息从拦截器发送到调用代码.
You should subclass IOException
and use that to send information from your interceptors to your calling code.
我们认为像IllegalStateException
这样的其他异常是应用程序崩溃,并且不要在线程边界上发送它们,因为我们不想让大多数调用者都无法捕获它们.
We consider other exceptions like IllegalStateException
to be application crashes and do not send them over thread boundaries because we don’t want to burden most callers with catching them.
这篇关于处理Kotlin Coroutines中的自定义okhttp拦截器引发的异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!