【问题标题】:Kotlin Coroutine : How to catch SocketTimeout Exception in InterceptorKotlin Coroutine:如何在拦截器中捕获 SocketTimeout 异常
【发布时间】:2020-01-07 15:39:09
【问题描述】:

我刚开始使用协程进行 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");
            }

【问题讨论】:

    标签: android coroutine socket-timeout-exception


    【解决方案1】:

    你需要一个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){
    
       }
    }
    

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

    【讨论】:

    • 谢谢,将尝试 coroutineExceptionHandler ....超时偶尔发生,所以我不知道这是否能解决我的问题,直到我可以重现。
    • 记得问throwable is SocketTimeOutException什么的
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-03-14
    • 2023-03-06
    • 1970-01-01
    • 1970-01-01
    • 2010-09-18
    • 2014-07-19
    • 1970-01-01
    相关资源
    最近更新 更多