Kotlin 协程:如何在拦截器中捕获 SocketTimeout 异常

Kotlin Coroutine : How to catch SocketTimeout Exception in Interceptor

我刚开始使用协程进行 2 个 运行 并行的异步调用。 aync 任务之一进行服务调用。此服务有时可能需要很长时间才能响应。在这种情况下,我的代码在我的匕首注入拦截器函数中崩溃。我试图捕获错误并将其扔回我的协程,但它从未被捕获。

协程:

    try {
                CoroutineScope(Dispatchers.IO).launch {

                    val deferredList = listOf(async {

                        myAPI?.getAllMarks(WebService.getAwsAccessToken(),
                                UserInfoManager?.userInfo?.guid)

                    }, async {

                        getClassFromJsonFile(R.raw.temp_whatsnew, WhatsNew::class.java)
                    })

                    var theList: List<Any> =
                            deferredList.awaitAll() // wait for all data to be processed without blocking the UI thread

                    withContext(Dispatchers.Main) {
                        mListener?.onWhatsNewDownloaded(theList.get(1) as WhatsNew,
                                theList.get(0) as List<Coachmark>)
                    }
                }
            } catch (t: Throwable) {
  //exception never reaches here!              
Log.v(WhatsNewInteractorImpl::class.java.simpleName, t.localizedMessage)

            }

拦截器:

try {
                response = chain.proceed(newRequest);
            } catch (SocketTimeoutException e) {
               //CRASHES HERE!
              throw new SocketTimeoutException("socket timeout");
            }

你需要 CoroutineExceptionHandler:

private val coroutineExceptionHandler = CoroutineExceptionHandler{_ , throwable -> 
  //handle error here
}

someScope.launch(Dispatchers.IO + coroutineExceptionHandler){

}

而且我建议不要在协程外部使用 try 和 catch,因为异常可能会从协程内部抛出。

其他选项:

scope.launch(Dispatchers.IO){
  try{
   //throwable operation
  }catch(e: SocketTimeOutException){

   }
}

或者你可以忘记错误处理,实现协程 method withTimeOut