解决 RxJava 报错 UndeliverableException The exception could not be delivered 崩溃修复
排查 RxJava 2/3 应用运行中突然因为 io.reactivex.rxjava3.exceptions.UndeliverableException 导致进程意外崩溃闪退,分析 下游取消订阅后上游异步异常投递(Undeliverable)与全局错误处理器。
问题现象
移动端或后端服务在网络中断后突然进程闪退退出,错误日志显示未捕获异常:
FATAL EXCEPTION: RxCachedThreadScheduler-1
io.reactivex.rxjava3.exceptions.UndeliverableException: The exception could not be delivered to the consumer because it has already canceled/disposed the flow
Caused by: java.io.IOException: Socket closed
触发根因
- 下游订阅者在特定时机(如页面关闭、用户取消操作或超时)主动调用了
disposable.dispose()取消订阅; - 上游的异步网络调用在稍后抛出了
IOException或网络断开异常; - 由于下游已经被注销,RxJava 无法将该异常沿着流正常传递给
onError,只能按照响应式流规范直接转交给全局未捕获异常处理器,导致整个进程崩溃。
解决步骤
在应用启动入口配置 RxJavaPlugins 全局安全错误拦截器
捕获并安全吞掉合理的无法投递网络异常:
RxJavaPlugins.setErrorHandler(e -> {
if (e instanceof UndeliverableException) {
e = e.getCause();
}
if (e instanceof IOException || e instanceof SocketException) {
// 忽略正常的网络取消中断:
log.warn("Fine: network interrupted after dispose: {}", e.getMessage());
return;
}
if (e instanceof InterruptedException) {
return;
}
log.error("Undeliverable exception received, not sure what to do", e);
});
确保在自定义 ObservableEmitter 中发射前检测 isDisposed()
避免盲目向下游推送数据。
验证确认
重新模拟高频取消网络请求:
异常被全局拦截器优雅降级吸收,进程长效常驻运行,闪退问题彻底根绝。


