Search code examples
spring-bootspring-mvcresttemplate

Rest Template pass original Message


I am building a (mostly) pass through API with RestTemplate which queries various different services. On errors and missing parameters the target APIs deliver error messages which go missing in the responses and I want to pass those through with the same HttpCode. Example:

curl -XPOST sourceapi:/...

{"type":"/errors/failed","title":"Entity Exists","details":"Entity with name \"test\" already exists","status":409}

If I do the same with a RestTemplate it throws and Exception and the message is null and it looks like this:

curl -XPOST testapi:/...

409 null

How can I pass error code as well as that object there down to the "client". (even logging it would be a start...)

I got a @ControllerAdvice class which already caches it but the message is actually just 409 null

  @ExceptionHandler(value = {HttpClientErrorException.class})
  public ResponseEntity<Object> clientErrorException(HttpClientErrorException ex) {
    return ResponseEntity.status(ex.getStatusCode()).body(ex.getMessage());
  }

Is there a way to add an ErrorParser or something while building the Template with RestTemplateBuilder?


Solution

  • Isn't getResponseBodyAsString() method (inherited from RestClientResponseException) what you seek?

      @ExceptionHandler(value = {HttpClientErrorException.class})
      public ResponseEntity<Object> clientErrorException(HttpClientErrorException ex) {
        return ResponseEntity.status(ex.getStatusCode()).body(ex.getResponseBodyAsString());
      }
    

    Or perhaps getResponseBodyAsByteArray() would be a better fit.