Skip to content

Commit

Permalink
Do not fixate on NonFatal for catchException
Browse files Browse the repository at this point in the history
  • Loading branch information
natsukagami committed Apr 12, 2024
1 parent 06b0a06 commit 5f55242
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 7 deletions.
11 changes: 6 additions & 5 deletions src/main/scala/dotty/result/package.scala
Original file line number Diff line number Diff line change
Expand Up @@ -389,16 +389,17 @@ object Result:
case Ok(value) => scala.util.Success(value)
case Err(error) => scala.util.Failure(error)

/** Evaluates `body`, catching [[scala.util.control.NonFatal NonFatal]]
* exceptions as errors.
/** Evaluates `body`, catching exceptions accepted by `catcher` as errors.
* @see
* [[scala.util.Try Try.apply]] for a similar method returning
* [[scala.util.Try]].
* [[scala.util.Try]], but works on all [[NonFatal]] exceptions.
* @group construct
*/
def catchException[T](body: => T): Result[T, Throwable] =
def catchException[T, E](catcher: PartialFunction[Throwable, E])(
body: => T
): Result[T, E] =
try Ok(body)
catch case NonFatal(ex) => Err(ex)
catch case ex => Err(catcher.applyOrElse(ex, _ => throw ex))

/** Right unit for chains of [[cons]]. An [[Ok]] with an [[EmptyTuple]] value.
* @group construct
Expand Down
11 changes: 9 additions & 2 deletions src/test/scala/result/Result.scala
Original file line number Diff line number Diff line change
Expand Up @@ -130,12 +130,19 @@ class ResultTest extends munit.FunSuite {
}

test("constructors") {
assertEquals(Result.catchException(1), Ok(1))
assertEquals(Result.catchException({ case ex => ex })(1), Ok(1))
val exc = new Exception("bleh")
assertEquals(Result.catchException(throw exc), Err(exc))
assertEquals(
Result.catchException({ case ex: Exception => ex })(throw exc),
Err(exc)
)

case object NoLog extends Exception("no log")

assert(
Try { Result.catchException({ case NoLog => 1 })(throw exc) }.isFailure
)

enum LogErr:
case NL(inner: NoLog.type)

Expand Down

0 comments on commit 5f55242

Please sign in to comment.