given a `Job`, how can I fail it with an exception...
# coroutines
z
given a
Job
, how can I fail it with an exception? I want to cancel it abnormally so its parent fails
z
“fail without an exception” is basically the definition of “cancellation”. Cancellation is failure without an exception, or failure with a
CancellationException
, and cancellation is just failure with an exception. They all use the same mechanism, just different words to describe different special cases.
z
yeah, that’s the problem. trying to have it fail, not just cancel
basically just trying to implement this:
Copy code
private fun Job.fail() {
    TODO("make this job fail with an exception")
}
z
job.cancel(RuntimeException("fail"))
?
z
that doesn’t actually compile anymore
only non-deprecated/hidden API for cancellation is
Copy code
fun cancel(cause: CancellationException? = null)
z
ugh, right, i always forget that. So
job.cancel(CancellationException(RuntimeException("fail")))
z
this seemed to do the trick, lol
Copy code
private fun CoroutineScope.fail() {
     try {
         runBlocking(this.coroutineContext) {
             @Suppress("RedundantAsync", "IMPLICIT_NOTHING_TYPE_ARGUMENT_IN_RETURN_POSITION")
             async(this@fail.coroutineContext) {
                 error("bad things!!")
             }
                 .await()
         }
     } catch (exception: IllegalStateException) {
     }
 }
z
I mean, if you really just want to cancel the parent, just get the parent job and cancel it
I have no idea what that code does haha
if you have to try that hard, i feel like it’s a sign something else is wrong
z
writing tests lol
not production code haha
z
I mean, tests are production code in that they are committed, they will probably outlast you, and other people have to maintain them – “it’s just tests” is no reason to write over-complicated code
z
I don’t feel this is too complicated. Just trying to write tests for the code I wrote, which requires a
job.fail()
function rather than
job.cancel()