[concurrency-interest] Layered exception handling with CompletableFuture

Zhong Yu zhong.j.yu at gmail.com
Wed Aug 27 12:45:43 EDT 2014


On Wed, Aug 27, 2014 at 8:56 AM, Peter Levart <peter.levart at gmail.com> wrote:
>
>         CompletableFuture<String> cf = CompletableFuture.supplyAsync(wrap(
>             () -> {
>                 double r = Math.random();
>                 if (r < 1d / 3d) return "OK";
>                 else if (r < 2d / 3d) throw new FileNotFoundException();
>                 else throw new EOFException();
>             }
>         ));
>
>         cf = cf.exceptionally(unwrapWrap(
>             (t) -> {
>                 try {
>                     throw t;
>                 } catch (IOException e) {
>                     throw new IllegalStateException("Converted from: " + e);
>                 }
>             }
>         ));
>
>         cf = cf.exceptionally(unwrapWrap(
>             (t) -> {
>                 try {
>                     throw t;
>                 } catch (RuntimeException e) {
>                     return "Handled: " + e;
>                 }
>             }
>         ));
>
>         System.out.println(cf.get());
>

Or... create a wrapper interface over CompletableFuture. The wrapper may
1. accept lambdas throwing checked exceptions
2. propagate cancellations by default
3. hide some methods (complete/obstrude) and expose some (cancel)
4. have shorter type/method names
5. reorg CF's methods, have fewer, composable methods
6. add more useful convenience methods

Zhong Yu
bayou.io


More information about the Concurrency-interest mailing list