【发布时间】:2021-04-09 10:44:46
【问题描述】:
我有一个在第二个元素上引发异常的简单流程:
private val log = LoggerFactory.getLogger("test")
fun main() = runBlocking {
flowOf(1, 2, 3)
.onCompletion { log.info("Flow completed${if (it == null) "" else " exceptionally: ${it.message}"}") }
.buffer()
.map { throwingMapper(it) }
.catch { log.error("Exception thrown") }
.collect { log.info(it) }
}
}
fun throwingMapper(it: Int): String {
if (it == 2) {
throw Exception("Test exception")
}
return "$it-mapped"
}
当我执行此代码时,我得到以下输出 - 流程完成无异常:
2021-04-09 12:35:00.875 [main] INFO - test:31 - Flow completed
2021-04-09 12:35:00.904 [main] INFO - test:133 - 1-mapped
2021-04-09 12:35:00.915 [main] ERROR - test:34 - Exception thrown
但是,当我将 map 运算符移到 buffer 之前:
flowOf(1, 2, 3)
.onCompletion { log.info("Flow completed${if (it == null) "" else " exceptionally: ${it.message}"}") }
.map { throwingMapper(it) }
.buffer()
.catch { log.error("Exception thrown") }
.collect { log.info(it) }
产生以下输出并完成流程例外情况:
2021-04-09 12:38:35.982 [main] INFO - test:31 - Flow completed exceptionally: Test exception
2021-04-09 12:38:36.024 [main] ERROR - test:34 - Exception thrown
在第一种情况下,流程是如何异常完成的? buffer 会默默吞下下游异常吗?还是它在内部创建了一个新流程?如果是这样,是否有一些保留原来的例外?
【问题讨论】:
标签: kotlin exception kotlin-coroutines kotlin-flow