I am facing a problem using a REST service made up with Spring Boot 1.5. I am developing a REST service that acts as a proxy, forwarding requests to another REST service that exposes the same API.
@RestController
@RequestMapping("/user")
public class ProxyUserController {
// Some initialization code
@PostMapping
public ResponseEntity<?> add(@Valid @RequestBody User user) {
return restTemplate.postForEntity(userUrl, user, String.class);
}
@Configuration
public static class RestConfiguration {
@Bean
public RestTemplate restTemplate(UserErrorHandler errorHandler) {
return new RestTemplateBuilder().errorHandler(errorHandler).build();
}
}
@Component
public static class UserErrorHandler implements ResponseErrorHandler {
@Override
public boolean hasError(ClientHttpResponse response) {
return false;
}
@Override
public void handleError(ClientHttpResponse response) {
// Empty body
}
}
}
As you can see, to avoid that RestTemplate
surrounds any error response with an exception that causes the creation of a new response with status 500
, I defined a customer ResponseErrorHandler
.
The problem I faced is that if the postForEntity
returns a response with an HTTP Status different from 200
, the response will never arrive at the caller, that hangs up until the timeout hits him.
However, if I create a new response starting from the one returned by the postForEntity
, all starts to work smoothly.
@PostMapping
public ResponseEntity<?> add(@Valid @RequestBody User user) {
final ResponseEntity<?> response =
restTemplate.postForEntity(userUrl, user, String.class);
return ResponseEntity.status(response.getStatusCode()).body(response.getBody());
}
What the hell is going on? Why I can't reuse a ResponseEntity
coming from another call?
Thanks to all.