错误处理在给定的界面的反应性,并命令性代码
之间的边界:错误处理在给定的界面的反应性,并命令性代码
public interface FastlyRxApi {
@GET("/service/{service_id}/version/{version}/backend")
Observable<List<Backend>> listBackends(@Path("service_id") String serviceId, @Path("version") String versionId);
@PUT("/service/{service_id}/version/{version}/backend/{old_name}")
Observable<Backend> updateBackend(@Path("service_id") String serviceId, @Path("version") String version, @Path("old_name") String oldName, @Body Backend updatedBacked);
}
和一些客户机代码:
Integer expectedFirstByteTimeout = 10000;
// Use a final array to capture any problem found within our composed Observables
final FastlyEnvException[] t = new FastlyEnvException[1];
fastlyRxApi.listBackends(serviceId, newVersion)
.flatMap(Observable::fromIterable)
.filter(backend -> !expectedFirstByteTimeout.equals(backend.getFirstByteTimeout()))
.flatMap(backend -> {
backend.setFirstByteTimeout(expectedFirstByteTimeout);
return fastlyRxApi.updateBackend(serviceId, newVersion, backend.getName(), backend);
}).subscribe(ignore -> {
}, e -> {
t[0] = new FastlyEnvException("failed to configure backends", e);
});
if (t[0] != null) {
throw t[0];
}
使用的FastlyEnvException
最终阵列以捕捉用于错误处理的上下文感觉自己在做错事,错过了某些方面。
我在这里使用锤子而不是螺丝刀;即我应该为此使用RxJava?除了错误处理外,它似乎给了我一个很好的可读流程。这样做的首选成语是什么?
使用onErrorResumeNext
:
.onErrorResumeNext(err ->
Observable.error(new FastlyEnvException("failed to configure backends", e)))
.toBlocking();
.subscribe();
这里注意到的是.toBlocking()
,这将使可观测链的等待,直到它完成。
鉴于subscribe()没有错误处理程序,它将重新抛出异常。
RxJava2,这样'blockingSubscribe()'? – jabley
正确。关键是等待操作完成,否则当您仍在提取数据时,最终可能会退出该方法。 –
只需在您的subscribe()
中省略错误处理程序,该错误将自动重新运行。
注意:'OnErrorNotImplementedException'将被抛出,但你可以通过'getCause()'方法获得你的原始异常。 –
在rxjava中处理错误的首选方法是在订阅中的onError块 –
这不是我上面所说的吗? 'onError'块在数组中存储一个异常。但感觉很笨拙。 – jabley
不完全。反应式编程失败只是另一种类型的通知,因此流可以完成或发出错误。所以在你的情况下,你不应该抛出任何例外来处理它们,你需要处理它们发生的地方,即你的订阅。还要阅读“反应性宣言”中的“反应性系统”部分,以更好地理解我的意思。 –