Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Throwables.getCauseAsOptional #3517

Open
RamAnvesh opened this issue Jun 28, 2019 · 1 comment
Open

Throwables.getCauseAsOptional #3517

RamAnvesh opened this issue Jun 28, 2019 · 1 comment

Comments

@RamAnvesh
Copy link

Throwables currently has

public static <X extends Throwable> X getCauseAs(Throwable throwable, Class<X> 
    expectedCauseType);

Can we add

public static Optional<X> getCauseAsOptional(Throwable throwable, Class<X> expectedCauseType){
    if(expectedCauseType.isInstance(throwable.getCause())){
      return Optional.of(expectedCauseType.cast(throwable.getCause()););
    } else {
      return Optional.empty();
    }
}

This enables clean conditional exception handling which can replace code this:

catch (ExecutionException e) {
    if ((e.getCause() instanceof AuthException)) {
        AuthException exception = (AuthException) e.getCause();
        if (exception.getCode().equals(AuthException.Code.USER_NOT_FOUND)) {
          // ignore the exception
        } else {
          throw e;
        }
      } else {
        throw e;
      }
}

with code like this:

catch (ExecutionException e) {
    getCauseAsOptional(e, AuthException.class)
        .map(authExp -> authExp.getCode())
        .filter(AuthException.Code.USER_NOT_FOUND::equals)
        .orElseThrow(() -> e);
}

The existing getCauseAs can be refactored to call this method internally.

@original-codematrix
Copy link

original-codematrix commented Apr 21, 2020

Can this be implemented?

@cpovirk cpovirk changed the title Feature Request: Add getCauseAsOptional to Throwables Throwables.getCauseAsOptional Apr 21, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

3 participants