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

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) {
if(errors == 2) {"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.