https://kotlinlang.org logo
#coroutines
Title
# coroutines
s

Sean Keane

05/27/2020, 12:41 PM
Hi All, I seem to have an issue with Coroutine Exception handler. I have created a scope that accepts a response callback.
Copy code
internal class MainScope<T>(private val coroutineContextProvider: CoroutineContextProvider, private val response: (Response<T>) -> Unit) : CoroutineScope {
    override val coroutineContext: CoroutineContext
        get() = coroutineContextProvider.context() + job + exceptionHandler

    private val job = SupervisorJob()

    //This needs more investigation with thread scope
    private val exceptionHandler = CoroutineExceptionHandler { _, throwable ->
        logWarn(throwable.message.orEmpty())
        response.invoke(Response(error = throwable, value = null))
    }
}
When an exception occurs I want to capture it and pass it back through the response object.
Copy code
class Response<out T>(val value:T?, val error: Throwable? = null) {

    fun isSuccess(block: (T) -> Unit): Response<T> {
        value?.let(block)
        return this
    }

    fun isFailure(block: (Throwable) -> Unit): Response<T> {
        error?.let(block)
        return this
    }

}
But the exception handler never gets called when a failure occurs. This is how I launch.
Copy code
MainScope(coroutineContextProvider, onResponse).launch { 
 //CODE
}
Am I missing something for handling the exception or should it just be captured when an exception occurs
f

fatih

05/27/2020, 7:16 PM
Why do you need to create your own scope? I think it seems like this can be done with giving your own exception handler directly to scope. For instance
val handler = CoroutineExceptionHandler{ context, exception -> response.doSomething(exception) }
And give it like
scope.launch(handler) {...}
s

Sean Keane

05/27/2020, 8:46 PM
I'll try that and see, I need to inject the same context so I can test so need them together.
👍 1
Found the issue. I had a run catching inside a class preventing the exception being thrown
2 Views