0

I'm reading a ResponseEntity from a webService using the Java (Spring 2.0) code below:

public ResponseEntity<?> getTemplate() {
    RestTemplate restTemplate = new RestTemplate();
    ResponseEntity<?> myResponse= restTemplate.postForEntity(
            myUrl, 
            myRequestObj, 
            MyResponseObj.class);
            
    return myResponse;
}

However, if the myUrl webservice returns HttpStatus.BAD_REQUEST (400) , this is not assigned to myResponse and an error is thrown, so there is no ResponseBody and I need to wrap the request in a try catch block. Is this correct or is there a way round this? Also, does this mean that the myUrl webservice should never intentionally (programatically) set the HttpStatus of myResponseObj to HttpStatus.BAD_REQUEST? So,even if myRequestObj contains bad data the myUrl webService should still set the response status to something in the 200's ie HttpStatus.NO_CONTENT. Any comments welcome on how to do this correctly.

DS.
  • 604
  • 2
  • 6
  • 24

1 Answers1

0

Is this correct or is there a way round this?

The behaviour you describe is defined by spring's detault error handler, which throws an HttpClientErrorException in case of a status code in the 400-499 range, an HttpServerErrorException in case of a status code in the 500-599 range and an UnknownHttpStatusCodeException if the status code is unknown. To handle such error codes you can either catch the exceptions or register a custom exception handler as described here.

Also, does this mean that the myUrl webservice should never intentionally (programatically) set the HttpStatus of myResponseObj to HttpStatus.BAD_REQUEST?

According to RFC 7231, the status code 400 is used to indicate that the server can't or won't process the request because of an error the client made creating the request (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). Therefore you are free to use that status code to indicate such behaviour to the client.

Community
  • 1
  • 1
Bernard
  • 333
  • 2
  • 8