如何在没有 subscribe() 的情况下处理 BlockingObservable 中的错误?

How to handle errors in BlockingObservable without subscribe()?

出于各种原因,我不得不像这样阻止 observable

Foo foo = fooBarNetworkRequestObservable()
   .toBlocking()
   .single();

return foo;

但是我现在该如何处理错误呢?没有 subscribe(new Subscriber .. onError()?) 是可能的吗?我尝试将代码包装在 try-catch 中,但编译器抱怨 IOException 从未在相应的 try-catch 块中抛出。任何解决方案?谢谢

你在阻塞世界中,所以你需要尝试捕捉。由于 API 不能抛出已检查的异常,我们为您将它们包装到 RuntimeException 中:

try {
    source.toBlocking.single();
} catch (RuntimeException ex) {
    if (ex.getCause() instanceof IOException) {
        // handle IOException
    } else {
        throw ex; // something other happened
    }
}