响应式微服务负本地的责管理失败。他们必须避免将失败传播到另一个微服务。换句话说,你不应该把这烫手的山芋委托给另一个微服务。因此,响应式微服务的代码将失败视为头等公民。
Vert.x开发模型使故障成为中心实体。当使用回调开发模型时,处理器通常会接收一个AsyncResult作为参数。这个结构封装了异步操作的结果。在成功的情况下,您可以检索结果。在失败中,它包含了一个描述失败的Throwable:
client.get("/").as(BodyCodec.jsonObject())
.send(ar -> {
if (ar.failed()) {
Throwable cause = ar.cause();
// You need to manage the failure.
} else {
// It's a success
JsonObject json = ar.result().body();
}
});
当使用RxJava API时候,错误处理可以放到subscribe中。
client.get("/").as(BodyCodec.jsonObject())
.rxSend()
.map(HttpResponse::body)
.subscribe(
json -> { /* success */ },
err -> { /* failure */ }
);
如果在所观察的stream中产生了故障,则会调用错误处理器。您还可以更早地处理失败,避免在subscribe方法中处理错误:
client.get("/").as(BodyCodec.jsonObject())
.rxSend()
.map(HttpResponse::body)
.onErrorReturn(t -> {
// Called if rxSend produces a failure
// We can return a default value
return new JsonObject();
})
.subscribe(
json -> {
// Always called, either with the actual result
// or with the default value.
}
);
管理错误并不好玩,但必须要做。响应式微服务的代码负责在遇到失败时作出适当的决定。它还需要准备好看到它对其他微服务的请求失败。