Throwing StopExecutionException from beforeTest/afterTest closure doesn't stop the execution of the task

Hi,
I have a task to fail build after x number of tests failed
I’m trying to implement this with the following approach:

test.afterTest { TestDescriptor td, TestResult tr ->
if(tr.resultType == TestResult.ResultType.FAILURE) {
    errors++
}
if(errors == 2) {
        logger.info("ERRORS: $errors")
        throw new StopExecutionException("Stoping after $errors failures")
    }

}

but the problem is I can’t see exception thrown in the logs and tests just keep going after 2 failures. during debugging I can see that this block of code is visited.