Exception not being caught in Coroutines

不想你离开。 提交于 2019-12-06 03:39:07
Jeel Vankhede

Trying with CoroutineExceptionHandler can be workaround for handling exceptions inside coroutines.

CoroutineExceptionHandler context element is used as generic catch block of coroutine where custom logging or exception handling may take place. It is similar to using Thread.uncaughtExceptionHandler.

How to use it?

val handler = CoroutineExceptionHandler { _, exception -> 
    println("Caught $exception") 
}
val job = GlobalScope.launch(handler) {
    throw AssertionError()
}
val deferred = GlobalScope.async(handler) {
    throw ArithmeticException() // Nothing will be printed, relying on user to call 
    deferred.await()
}
joinAll(job, deferred)

In your ViewModel, make sure that your uiScope is using SupervisorJob rather than Job. SupervisorJob's can handle its children's failure individually. Job would get cancelled unlike SupervisorJob

If you're using 2.1.0 for AAC Lifecycle and ViewModel, use the viewModelScope extension instead.

As far as I know Retrofit hasn't still created the way to mark the methods with the suspend keyword. You can refer it to this link. So the correct way of your MyInterface would be:

interface MyInterface {
    @POST
    fun doSomething(): Deferred<Response<YourDataType>>
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!