我正在学习 RxScala 并来到这个非常合成的片段。我正在尝试处理 onError 块中的异常:
def doLongOperation():String = {
(1 to 10).foreach {
_ =>
Thread.sleep(100)
print(".")
}
println()
if (System.currentTimeMillis() % 2 == 0) {
throw new RuntimeException("Something went wrong during long operation")
}
s"OK"
}
def main(args: Array[String]) {
println("Changing status: -> doing task1")
Observable.just(
doLongOperation()
).subscribe(
str => println("Changing status: doing task1 -> doing task2"),
throwable => println(s"Failed: ${throwable.getMessage}"), //never get here
() => println("Completed part")
)
}
万一出现异常,我希望是这样的:
Failed: Something went wrong during long operation
但我得到的是:
.........Exception in thread "main" java.lang.RuntimeException: Something went wrong during long operation
at stats.STest$.doLongOperation(STest.scala:20)
at stats.STest$.main(STest.scala:49)
at stats.STest.main(STest.scala)
我错过了什么?我应该在观察者处“手动”调用 onError 吗?感谢任何帮助。