Calling Micro-service using WebClient Sprint 5 reactor web

Deadly 提交于 2019-12-12 04:23:59

问题


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));
}

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.


回答1:


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());


来源:https://stackoverflow.com/questions/42045267/calling-micro-service-using-webclient-sprint-5-reactor-web

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!