Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

How to handle return type and exception on Spring WebFlux Webclient

In my controller I call a service layer to return the result of a webflux webclient which in turn sends requests to another microservice.

The microservice can either return the matching Object or potentially throw an exception which comes back in application/json+problem header.

My controller is simply the following:

    public ResponseEntity<MyDTO> create(@Valid @RequestBody final MyDTO myDTO) throws URISyntaxException {
        log.debug("REST request to create : {}", myDTO);

        Object response = myService.create();

        MyDTOresult = new ObjectMapper().convertValue(response , MyDTO.class);
        return ResponseEntity.ok().body(result);
    }

And my webclient service layer:

                webClient
                .post()
                .uri(MY_URL)
                .accept(MediaType.APPLICATION_JSON)
                .body(BodyInserters.fromValue(myDTO))
                .retrieve()
                .onStatus(HttpStatus::isError, response -> response.bodyToMono(String.class)
                    .flatMap(error -> Mono.error(new RuntimeException(error))))
                .bodyToMono(Object.class)
                .block();

The issue I'm facing is that if the exception handling is not being triggered, not sure what I'm missing here as essentially I want a generic exception parser to catch the unsuccessful responses and stop the process there and then, but at the moment I think this is attempting to map it to Object.class, (Content type 'application/problem+json' not supported for bodyType=java.lang.Object).

Thanks

question from:https://stackoverflow.com/questions/65883559/how-to-handle-return-type-and-exception-on-spring-webflux-webclient

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...