Skip to content

Commit

Permalink
rx (feature): Add Rx.trasnformFailure for error handling (#3214)
Browse files Browse the repository at this point in the history
  • Loading branch information
xerial authored Sep 11, 2023
1 parent 86fbc24 commit 4899072
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 0 deletions.
18 changes: 18 additions & 0 deletions airframe-rx/src/main/scala/wvlet/airframe/rx/Rx.scala
Original file line number Diff line number Diff line change
Expand Up @@ -312,6 +312,12 @@ trait Rx[+A] extends RxOps[A] {
TransformRxOp(this, f)
}

/**
* Transform a Success(v) or Failure(Throwable) input with a given function.
* @param f
* @tparam B
* @return
*/
def transform[B](f: Try[A] => B): Rx[B] = {
TransformOp(this, f)
}
Expand All @@ -324,6 +330,18 @@ trait Rx[+A] extends RxOps[A] {
TransformTryOp(this, f)
}

/**
* Transform a specific type of an exception into another exception. This is useful for handling exceptions.
* @param f
* @return
*/
def transformFailure(f: PartialFunction[Throwable, Throwable]): Rx[A] = {
transformTry[A] {
case Failure(ex) if f.isDefinedAt(ex) => Failure(f.apply(ex))
case other => other
}
}

def concat[A1 >: A](other: Rx[A1]): Rx[A1] = Rx.concat(this, other)
def lastOption: RxOption[A] = LastOp(this).toOption

Expand Down
13 changes: 13 additions & 0 deletions airframe-rx/src/test/scala/wvlet/airframe/rx/RxTransformTest.scala
Original file line number Diff line number Diff line change
Expand Up @@ -95,4 +95,17 @@ class RxTransformTest extends AirSpec {
fail(s"Unexpected: ${other}")
}
}

test("Rx.transformFailure") {
Rx.fromTry(Failure(new UnsupportedOperationException("N/A")))
.transformFailure { case ex: UnsupportedOperationException =>
new IllegalStateException("unimplemented")
}
.recover {
case e: IllegalStateException =>
"ok"
case other =>
fail(s"Unexpected: ${other}")
}
}
}

0 comments on commit 4899072

Please sign in to comment.