1

I'm trying to log at each failure stage and, as far as I can tell, I need to nest the try and log inside a flatmap.

Try.of(() -> true).
    onFailure(h -> System.out.println("first onFailure")).
    flatMap(i -> Try.of(() -> { throw new RuntimeException(); }).
                     onFailure(j -> System.out.println("second onFailure"))).
    flatMap(k -> Try.of(() -> true).
                     onFailure(l -> System.out.println("third onFailure")));

Is there an easier way to do it than the above? Is there a function in the library that I can use to replace the nested Try.of()s?

Richard Polton
  • 101
  • 1
  • 5

2 Answers2

0

Why do you nest the onFailure calls? How about this syntax?

Try.of(() -> true)
        .onFailure(h -> System.out.println("first onFailure"))
        .flatMap(i -> Try.of(() -> { throw new RuntimeException(); }))
        .onFailure(j -> System.out.println("second onFailure"))
        .flatMap(k -> Try.of(() -> true)
        .onFailure(l -> System.out.println("third onFailure")));
Sir4ur0n
  • 1,753
  • 1
  • 13
  • 24
  • If I read what you have written correctly, if the of() 'throws' then this will log three times, which I don't want to do – Richard Polton Aug 28 '18 at 08:30
  • 1
    My bad. Then I don't think it's possible. Unless you're willing to do some kind of pattern matching once and for all in an `onFailure` after the flatmaps (e.g. using `recover`), your workflow is not linear short circuiting in case of error (and flatmap is useful for this). – Sir4ur0n Aug 28 '18 at 10:31
0

If you want just log failures you can do it once:

Try.of(() -> method1())
        .mapTry(i -> method2())
        .mapTry(k -> method3())
        .onFailure(throwable -> log.error("Something wrong", throwable));
Alexander Pankin
  • 3,787
  • 1
  • 13
  • 23
  • Thanks, but I want to be able to log the failures per sub-clause instead of on the entire statement – Richard Polton Aug 28 '18 at 08:30
  • @RichardPolton Just edited answer. As I see it, exception's stack trace can show wich sub-clause failed. But if you want more control, you should use nested Try.of() – Alexander Pankin Aug 28 '18 at 10:27