'Jenkins Pipeline DSL: Can I conditionally retry an entire stage?

Sometimes our Jenkins stage fails with the following error:

Emulator did not finish booting within 600 seconds, aborting

This usually happens because the VM has entered some type of low memory state and any subsequent attempts to boot the emulator on that VM will failure. So in this scenario, I'd like to automatically re-execute the entire stage as a whole (should hopefully automatically be assigned a new VM). How can I achieve this?

There's options { retry(3) }

stage("android-ui-tests") {
  options {
    retry(3) 
  }
  steps {
      // run stage..
  }
}

But AFAIK, this is not conditional. An API like the following would be ideal:

options {
  retry(3) {
    if(exception.contains("Emulator did not finish booting")) {
      // `true` to retry
      return true
    }
    return false
  } 
}

Does anything like this exist? Or maybe a post condition that could inspect the failure and trigger a retry?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source