Skip to content

Commit 4899072

Browse files
authored
rx (feature): Add Rx.trasnformFailure for error handling (#3214)
1 parent 86fbc24 commit 4899072

File tree

2 files changed

+31
-0
lines changed

2 files changed

+31
-0
lines changed

airframe-rx/src/main/scala/wvlet/airframe/rx/Rx.scala

+18
Original file line numberDiff line numberDiff line change
@@ -312,6 +312,12 @@ trait Rx[+A] extends RxOps[A] {
312312
TransformRxOp(this, f)
313313
}
314314

315+
/**
316+
* Transform a Success(v) or Failure(Throwable) input with a given function.
317+
* @param f
318+
* @tparam B
319+
* @return
320+
*/
315321
def transform[B](f: Try[A] => B): Rx[B] = {
316322
TransformOp(this, f)
317323
}
@@ -324,6 +330,18 @@ trait Rx[+A] extends RxOps[A] {
324330
TransformTryOp(this, f)
325331
}
326332

333+
/**
334+
* Transform a specific type of an exception into another exception. This is useful for handling exceptions.
335+
* @param f
336+
* @return
337+
*/
338+
def transformFailure(f: PartialFunction[Throwable, Throwable]): Rx[A] = {
339+
transformTry[A] {
340+
case Failure(ex) if f.isDefinedAt(ex) => Failure(f.apply(ex))
341+
case other => other
342+
}
343+
}
344+
327345
def concat[A1 >: A](other: Rx[A1]): Rx[A1] = Rx.concat(this, other)
328346
def lastOption: RxOption[A] = LastOp(this).toOption
329347

airframe-rx/src/test/scala/wvlet/airframe/rx/RxTransformTest.scala

+13
Original file line numberDiff line numberDiff line change
@@ -95,4 +95,17 @@ class RxTransformTest extends AirSpec {
9595
fail(s"Unexpected: ${other}")
9696
}
9797
}
98+
99+
test("Rx.transformFailure") {
100+
Rx.fromTry(Failure(new UnsupportedOperationException("N/A")))
101+
.transformFailure { case ex: UnsupportedOperationException =>
102+
new IllegalStateException("unimplemented")
103+
}
104+
.recover {
105+
case e: IllegalStateException =>
106+
"ok"
107+
case other =>
108+
fail(s"Unexpected: ${other}")
109+
}
110+
}
98111
}

0 commit comments

Comments
 (0)