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

Add other exceptions from race as suppressed #100

Merged
merged 1 commit into from
Mar 14, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 8 additions & 1 deletion core/src/main/scala/ox/race.scala
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,14 @@ def race[E, F[_], T](em: ErrorMode[E, F])(fs: Seq[() => F[T]]): F[T] =

@tailrec
def takeUntilSuccess(failures: Vector[Either[E, Throwable]], left: Int): F[T] =
if left == 0 then failures.headOption.getOrElse(throw new NoSuchElementException).fold(em.pureError, throw _)
if left == 0 then
val otherExceptions = failures.tail.collect { case Right(e) => e }
failures.headOption.getOrElse(throw new NoSuchElementException) match
case Left(appError) =>
otherExceptions.foldLeft(em.pureError(appError))(em.addSuppressed)
case Right(e) =>
otherExceptions.foreach(ee => if e != ee then e.addSuppressed(ee))
throw e
else
result.take() match
case Success(v) =>
Expand Down
18 changes: 18 additions & 0 deletions core/src/test/scala/ox/RaceTest.scala
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,24 @@ class RaceTest extends AnyFlatSpec with Matchers {
end - start should be < 1000L
}

it should "add other exceptions as suppressed" in {
try
race(
throw new RuntimeException("boom1!"), {
Thread.sleep(200)
throw new RuntimeException("boom2!")
}, {
Thread.sleep(200)
throw new RuntimeException("boom3!")
}
)
fail("Race should throw")
catch
case e: Exception =>
e.getMessage shouldBe "boom1!"
e.getSuppressed.map(_.getMessage).toSet shouldBe Set("boom2!", "boom3!")
}

"raceEither" should "return the first successful computation to complete" in {
val trail = Trail()
val start = System.currentTimeMillis()
Expand Down
Loading