Home > Back-end >  How to cancel SupervisorJob based on the type of exception thrown by the child coroutine
How to cancel SupervisorJob based on the type of exception thrown by the child coroutine

Time:04-08

I have a supervisor that launches some children coroutines

        supervisorScope {
               aListOfJobs.forEach { job -> launch(handler) { process(job) } }
            }
        }

Where handler is some callback to handle the thrown exceptions from the children coroutines.

    val handler = CoroutineExceptionHandler { _, exception ->
        
       // for some exceptions I should allow the parent job to continue, and others I should not and trigger the cancellation of my parent
    }

It seems that even when the handler throws an exception (i.e. i rethrow the received exception), the supervisor is not cancelled.

So my question is, what is the idiomatic way to allow the supervisor to continue working for some exceptions, but not others?

CodePudding user response:

If answering: "what is the idiomatic way to allow the supervisor to continue working for some exceptions, but not others?" I agree with @IR42. If we have many different types of exceptions and we would like to ignore some of them and fail on others, it is probably clearer to fail by default and ignore in specific cases.

However, if your case is that you generally ignore all errors, but you fail on one or a few specific ones (like explicit "abort" exception), then you can invoke cancel() manually:

supervisorScope {
    aListOfJobs.forEach { job ->
        launch {
            try {
                process(job)
            } catch (e: AbortException) {
                [email protected]("message", e)
                throw e
            }
        }
    }
}

CodePudding user response:

You can't do this with CoroutineExceptionHandler, instead you should use coroutineScope and try catch

try {
    coroutineScope {
        aListOfJobs.forEach { job ->
            launch {
                try {
                    process(job)
                } catch (e: WorkShouldСontinueExceprion) {
                }
            }
        }
    }
} catch (e: WorkShouldStopExceprion) {
}
  • Related