1

I am trying to send bad request from spring boot rest for validation error. Below is my method

public ResponseEntity<?>  getMyData(@Valid @ModelAttribute InputParms ipParms,BindingResult bindingResult )   {  

    MyObject obj=new MyObject ();

    if(bindingResult.hasErrors()) {
        return ResponseEntity.status(400).body(obj);
    }

    //my other code

}

On client side I have something like below. But it is throwing exception and code is not even reaching if block.

ResponseEntity<MyObject > resultResp=restTemplate.postForEntity(url,inputParam, MyObject .class);        
if(resultResp.getStatusCode().equals(HttpStatus.OK)) {
    //my success code
}else {
    //my bad response code 
} 

In the same code if i send status 200, it is working. What is I am doing wrong here.

user9735824
  • 1,196
  • 5
  • 19
  • 36

1 Answers1

2

By default RestTemplate will throw an exception on a 4xx error. Instead of checking for the status code in the ResponseEntity, wrap the call in a subclass of RestClientException, for example:

try {
    ResponseEntity<MyObject> resultResp = restTemplate.postForEntity(url,inputParam, MyObject .class);        
} catch (HttpStatusCodeException e) {
    System.out.println("Error from server: " + e.getStatusCode() + " - " + e.getResponseBodyAsString());
}

You could even catch HttpClientErrorException or HttpServerErrorException separately and handle errors differently for a 4xx and a 5xx error.

nickb
  • 59,313
  • 13
  • 108
  • 143