Kotlin coroutines - gracefully handling errors from suspend functions

后端 未结 1 1314
伪装坚强ぢ
伪装坚强ぢ 2021-01-21 16:13

Trying to implement graceful handling of the errors with suspend functions that are called from async methods, How to catch the error thrown by a suspend method.

         


        
相关标签:
1条回答
  • 2021-01-21 16:49

    I would use a CoroutineExceptionHandler to make your coroutines fail gracefully:

    1) Define the handler:

    val exceptionHandler = CoroutineExceptionHandler { context, error ->
        // Do what you want with the error
        Log.d(TAG, error)
    }
    

    2) Refactor your findById function to be executed within an IO context and make your ui code main safe:

    suspend fun findById(id : Int) : User? = withContext(Dispatchers.IO){
        when(id){
            0 -> throw Exception("not valid")
            else -> return@withContext User(id)
        }
    }
    
    1. Launch your job within MainScope (and so update the ui), passing exceptionHandler to launch coroutine builder in order to catch the exception:
    val exceptionHandler = CoroutineExceptionHandler { _, error ->
         // Do what you want with the error
        Log.d(TAG, error)
    }
    
    MainScope().launch(exceptionHandler) {
         val user = delegate?.findById(userId)
            user?.let {
                Timber.v(it.toString())
            }
    }
    
    0 讨论(0)
提交回复
热议问题