使用WebClient Sprint 5 reactor web调用微服务 [英] Calling Micro-service using WebClient Sprint 5 reactor web

查看:31
本文介绍了使用WebClient Sprint 5 reactor web调用微服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在我的休息控制器中调用微服务.当微服务成功响应时,它工作正常,但如果有一些错误响应,我无法将错误响应传递回用户.下面是示例代码.

I am calling a micro-service in my rest controller. It works fine when ever there is a successful response from the Micro-service but if there is some error response I fails to pass on the error response back to user. Below is the sample code.

 @GetMapping("/{id}/users/all")
public Mono<Employee> findAllProfiles(@PathVariable("id") UUID organisationId,
                                           @RequestHeader(name = "Authorization", required = false) String oauthJwt) {
    return webClient.get().uri(prepareUrl("{id}/users/all"), organisationId)
            .header("Authorization", oauthJwt).accept(MediaType.APPLICATION_JSON)
            .exchange().then(response -> response.bodyToMono(Employee.class));
}

现在,如果有任何带有错误代码的 JSON 响应,则 Web 客户端不会将错误响应传递给控制器​​,因为不会将任何信息传播给 api 最终用户.

Now if there is any JSON response with error code then web client does not pass on the error response to the controller due to which no information is propagated to the api end user.

推荐答案

您应该能够从 Mono API.查找onError"以查看多个选项,这些选项允许您定义出现错误时的行为.

You should be able to chain methods from the Mono API. Look for "onError" to see a number of options which allow you to define the behavior when there is an error.

例如,如果您想返回一个空"员工,您可以执行以下操作:

For example, if you wanted to return an "empty" Employee, you could do the following:

.exchange()
.then(response -> response.bodyToMono(Employee.class))
.onErrorReturn(new Employee());

这篇关于使用WebClient Sprint 5 reactor web调用微服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆