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

Proposal: Future.recover() doesn't take a CheckedFunction. #2638

Closed
qux42 opened this issue Feb 5, 2021 · 2 comments
Closed

Proposal: Future.recover() doesn't take a CheckedFunction. #2638

qux42 opened this issue Feb 5, 2021 · 2 comments

Comments

@qux42
Copy link

qux42 commented Feb 5, 2021

Hello,

I have quite often the use case that I have a Future, that i want to recover in case a certain Exception was thrown.
This is currently only with future.RecoverWith() possible. But this adds bulkiness, because you have to create and return a new Future.

So currently the code looks like that:

final Future<String> recovered = failedFuture.recoverWith(throwable -> {
                if (throwable instanceof RuntimeException) {
                    return Future.successful("yeah");
                }
                return Future.failed(throwable);
            });

Is it possible that the recover method can be changed to accept a CheckedFunction instead?
Then it would be possible to write following code:

final Future<String> recovered = failedFuture.recover(throwable -> {
                if (throwable instanceof RuntimeException) {
                    return "yeah";
                }
                throw throwable;
            });

If so I could assist with an PullRequest.

Thanks

@qux42 qux42 changed the title Future.recover() doesn't take a CheckedFunction. Proposal: Future.recover() doesn't take a CheckedFunction. Feb 27, 2021
@danieldietrich
Copy link
Contributor

danieldietrich commented Apr 11, 2021

Try has similar methods, e.g. recover(Class, Function).

The recover function would need to run async with the same executor. This would be a solution (applied to the Future interface):

default <X extends Throwable> Future<T> recover(Class<X> exceptionType, Function<? super X, ? extends T> f) {
    Objects.requireNonNull(exceptionType, "exceptionType is null");
    Objects.requireNonNull(f, "f is null");
    return transformValue(t -> t.recover(exceptionType, f));
}

A PR is appreciated!

@sleepytomcat
Copy link
Contributor

Let me jump in with PR #2671

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