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.
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)
}
}
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())
}
}