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 the Result#fromCatchingNonFatal #590

Merged
merged 2 commits into from
Aug 23, 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
19 changes: 19 additions & 0 deletions chimney/src/main/scala/io/scalaland/chimney/partial/Result.scala
Original file line number Diff line number Diff line change
Expand Up @@ -591,6 +591,25 @@ object Result {
case t: Throwable => fromErrorThrowable(t)
}

/** Converts possibly throwing computation into [[io.scalaland.chimney.partial.Result]] by catching only
* [[scala.util.control.NonFatal NonFatal Exceptions]].
*
* @tparam A
* type of successful result
* @param value
* computation to run while catching its [[scala.util.control.NonFatal NonFatal Exceptions]]
* @return
* successful [[io.scalaland.chimney.partial.Result.Value]] if computation didn't throw, failed
* [[io.scalaland.chimney.partial.Result.Errors]] with caught Exception if it threw
* @since 1.5.0
*/
final def fromCatchingNonFatal[A](value: => A): Result[A] =
try
fromValue(value)
catch {
case scala.util.control.NonFatal(t) => fromErrorThrowable(t)
}

/** Converts an [[scala.collection.Iterator]] of input type into selected collection of output type, aggregating
* errors from conversions of individual elements.
*
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -266,6 +266,23 @@ class PartialResultSpec extends ChimneySpec {
partial.Result.fromCatching(throw exception) ==> partial.Result.fromErrorThrowable(exception)
}

test("fromCatchingNonFatal converts thunk to Result caching NonFatal Throwable as Error") {
val nseEx = new NoSuchElementException("oops")
partial.Result.fromCatchingNonFatal(1) ==> partial.Result.fromValue(1)
partial.Result.fromCatchingNonFatal(throw nseEx) ==> partial.Result.fromErrorThrowable(nseEx)
}

test("fromCatchingNonFatal propagates Fatal Throwable") {
try
partial.Result.fromCatchingNonFatal(throw new OutOfMemoryError("oops"))
catch {
case _: VirtualMachineError =>
()
case th: Throwable =>
throw th
}
}

test(
"traverse with failFast = false preserves parallel semantics (both branches are executed even if one of them fails)"
) {
Expand Down
Loading