2

I have this code :

ResponseEntity<DTODemo> responseEntity = webClient.get()
                .uri("http://localhost:8051/callAPI/")
                .retrieve()
                .toEntity(DTODemo.class)
                .block();

It work, when my api return an object DTODemo. But, the API can return with code HTTP 404 a message in the body ( type String). I have this exception :

org.springframework.web.reactive.function.UnsupportedMediaTypeException: Content type 'text/plain;charset=UTF-8' not supported for bodyType=com.example.demo.DTODemo 

I try many of things but i haven't found a good solution.

Any idea to solve my problem using retrieve and not exchange ?

Thanks a lot.

lkatiforis
  • 5,703
  • 2
  • 16
  • 35
Samshay
  • 123
  • 1
  • 2
  • 10

2 Answers2

0

You can specify the set of acceptable media types, as specified by the Accept header. For example,

ResponseEntity<DTODemo> responseEntity = webClient.get()
                .uri("http://localhost:8051/callAPI/")
                .accept(MediaType.APPLICATION_JSON)
                .retrieve()
                .toEntity(DTODemo.class)
                .block();
Dharman
  • 30,962
  • 25
  • 85
  • 135
-1

I suggest to create a custom Exception class DtoNotFoundException for instance and surround your code with try/catch block and catch the UnsupportedMediaTypeException the throw your custom exception so you can catch it in any other piece of code and do whatever you want

import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;

@ResponseStatus(code = HttpStatus.NOT_FOUND, reason = "Dto not found")
public class DtoNotFoundException extends RuntimeException {

    public DtoNotFoundException() {
    }

    public DtoNotFoundException(String message) {
        super(message);
    }
}

then your code can be like that :

try{
    ResponseEntity<DTODemo> responseEntity = webClient.get()
                    .uri("http://localhost:8051/callAPI/")
                    .retrieve()
                    .toEntity(DTODemo.class)
                    .block();
}catch(UnsupportedMediaTypeException e){
    throw new DtoNotFoundException("Dto not found");
}

so if you have a scenario using your code you can catch your custom exception and take an action like returning 404 response code with the exception message

     @GetMapping("/dto")
    ResponseEntity<?> getDto() {
        try {
            var dtoUseExample = this.yourService.yourClientFunction() // request done;
        } catch (DtoNotFoundException e) {
            throw new ResponseStatusException(HttpStatus.NOT_FOUND, e.getMessage());
        }
    }