Skip to content
This repository has been archived by the owner on Oct 14, 2023. It is now read-only.

Commit

Permalink
[jOOQ#91] Added Seq.peekThrowable()
Browse files Browse the repository at this point in the history
  • Loading branch information
Tomasz Linkowski committed May 17, 2017
1 parent ece5497 commit 62b9c61
Show file tree
Hide file tree
Showing 2 changed files with 59 additions and 0 deletions.
15 changes: 15 additions & 0 deletions src/main/java/org/jooq/lambda/Seq.java
Original file line number Diff line number Diff line change
Expand Up @@ -431,6 +431,21 @@ default <X extends Throwable> Seq<T> onEmptyThrow(Supplier<? extends X> supplier
});
}

/**
* If a throwable occurs during traversal of elements, call the <code>throwableHandler</code>
* on this throwable before rethrowing it.
*/
default Seq<T> peekThrowable(Consumer<? super Throwable> throwableHandler) {
return SeqUtils.transform(this, (delegate, action) -> {
try {
return delegate.tryAdvance(action);
} catch (Throwable throwable) {
throwableHandler.accept(throwable);
throw throwable;
}
});
}

/**
* Concatenate two streams.
* <p>
Expand Down
44 changes: 44 additions & 0 deletions src/test/java/org/jooq/lambda/SeqTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -987,6 +987,50 @@ public void testOnEmpty() {
assertEquals(asList(2, 3), Seq.of(2, 3).onEmptyThrow(() -> new X()).toList());
}

@Test
public void testPeekThrowable() {
class PeekedX extends RuntimeException {}

Function<Integer, Consumer<Integer>> throwXUpon = i -> j -> {
if (i.equals(j)) {
throw new X();
}
};
Consumer<Throwable> rethrowAsPeekedX = ex -> {
throw new PeekedX();
};

// assert throws X
assertThrows(X.class, () -> Seq.of(1, 2, 3)
.peek(throwXUpon.apply(2))
.toList());

// assert throws PeekedX when "peekThrowable" AFTER "throw"
assertThrows(PeekedX.class, () -> Seq.of(1, 2, 3)
.peek(throwXUpon.apply(2))
.peekThrowable(rethrowAsPeekedX)
.toList());

// assert throws PeekedX EVEN when "peekThrowable" BEFORE "throw" but on the SAME Spliterator
assertThrows(PeekedX.class, () -> Seq.of(1, 2, 3)
.peekThrowable(rethrowAsPeekedX)
.peek(throwXUpon.apply(2))
.toList());

// assert throws X when "peekThrowable" on DIFFERENT Spliterator than "throw"
assertThrows(X.class, () -> Seq.of(1, 2, 3).peekThrowable(rethrowAsPeekedX)
.append(Seq.of(4, 5, 6).peek(throwXUpon.apply(5)))
.toList());

// assert throws PeekedX in a complex Seq
assertThrows(PeekedX.class, () -> Seq.of(1, 2, 3)
.flatMap(i -> Seq.of(4 * i, 5 * i, 6 * i).peek(throwXUpon.apply(10)))
.filter(i -> i % 2 != 0)
.limitWhile(i -> i <= 9)
.peekThrowable(rethrowAsPeekedX)
.toList());
}

@SuppressWarnings("serial")
static class X extends RuntimeException {}

Expand Down

0 comments on commit 62b9c61

Please sign in to comment.