Resttemplate not working if there is bad request


Resttemplate not working if there is bad request



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.




1 Answer
1



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:


RestClientException


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.


HttpClientErrorException


HttpServerErrorException






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Comments

Popular posts from this blog

paramiko-expect timeout is happening after executing the command

Opening a url is failing in Swift

Possible Unhandled Promise Rejection (id: 0): ReferenceError: user is not defined ReferenceError: user is not defined