Hi All, I seem to have an issue with Coroutine Ex...
# coroutines
s
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
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
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