【问题标题】:Return value from a CorutineExectionHandler to the calling method从 CorutineExectionHandler 返回值到调用方法
【发布时间】:2022-01-06 08:42:43
【问题描述】:

是否可以从 CoroutineExceptionHandler 向调用方法返回值?

 override suspend fun getStatus() : Model {        
return withContext<Model>(Dispatchers.IO + errorHandler) {
                //Do something and return model
                // If any other exception is thrown while multiple coroutines its passed down to errorhanlder
        }
    }


 private val errorHandler = CoroutineExceptionHandler { _, exception ->
        
    }

【问题讨论】:

    标签: android kotlin-coroutines android-mvvm


    【解决方案1】:

    不,不是。

    这种处理程序用于一般未捕获的异常处理,并且可以在许多不同的协程中重用,这些协程可能期望不同的返回值,甚至可能根本不返回值。

    如果您想捕获一些异常并返回一个不同的值,您需要使用try/catch 块当场(例如在您的withContext 周围)执行此操作:

    override suspend fun getStatus() : Model = try {
        withContext<Model>(Dispatchers.IO) {
            // Do something and return model
        }
    } catch(e: Exception) { // use more specific exception if you can
        SomeErrorModel(...)
    }
    

    【讨论】:

      猜你喜欢
      • 2019-07-11
      • 1970-01-01
      • 2013-12-24
      • 1970-01-01
      • 2016-01-14
      • 2019-01-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多