failsafe-lib / failsafe

Fault tolerance and resilience patterns for the JVM
https://failsafe.dev
Apache License 2.0
4.2k stars 297 forks source link

"sneaky throw" original Exception instead of FailsafeException when retries exceeded #331

Closed RG9 closed 2 years ago

RG9 commented 2 years ago

test:

    @Test
    void shouldRethrowOriginalException() {
        assertThatThrownBy(() -> Failsafe.with(RetryPolicy.ofDefaults())
            .run(() -> {
                throw new IOException();
            }))
                .isInstanceOf(FailsafeException.class);
    }

my current workaround:

 try {
      Failsafe.with(retryPolicy).run(taskThrowingIoException);
  } catch (FailsafeException e) {
      throw sneakyThrow(e.getCause());
  }

 @SuppressWarnings("unchecked")
  private static <T extends Throwable, R extends RuntimeException> R sneakyThrow(Throwable t) throws T {
      throw (T) t;
  }

Is there any better way to deal with it?

jhalterman commented 2 years ago

I think the only improvement would be for Failsafe to add an option to support sneaky throws, ex:

Failsafe.with(policy).withSneakyThrows().run(this::doSomething);

I've always wondered if this would be requested, but surprisingly it hasn't so far. Is unwrapping checked exceptions just inconvenient for you?

RG9 commented 2 years ago

Thanks for answer. I think I just tried to implement an overly generic solution. After narrowing down the scope, unwrapping is also fine :+1: Besides, from my understanding, checked exceptions were designed to support recover from error, but actually this is where Failsafe takes the baton.

jhalterman commented 2 years ago

Good to hear. I'll close this issue for now then.