简体   繁体   中英

Spring Boot: returned HTTP response code 400, nested exception is java.io.IOException

Consider the below code.Here, when the status code returned by the response is 200, then code execution works perfectly.

But if I try to return the status code 400, then Exception is caught at the specified line.

* Error Response : Internal Server Error in: getResponse I/O error on POST request for "http://localhost:8090/get-data": Server returned HTTP response code: 400 for URL: http://localhost:8090/get-data; nested exception is java.io.IOException: Server returned HTTP response code: 400 for URL: http://localhost:8090/get-data

connection: close, content-length: 485, content-type: application/json, date: Thu, 08 Apr 2021 20:25:47 GMT*

Why is an exception thrown when status 400 is returned?

 @RestController
    Class ABC{
    
        @Autowired
        RestTemplate template;
    
        @PostMapping("....")
        ResponseEntity<Object> getResponse(){
            ResponseEntity<String> response
            try{
              HttpEntity<Object> body=new HttpEntity(obj,header); // data obj & httpheader
              response=template.postForEntity("http://localhost:8090/get- 
                       data",body,String.class);
            }catch(HttpStatusCodeException ex){
                  throw....
            }catch(Exception ex){
                throw Internal Server Error.....  //Exception is thrown here
            }       
            if(response.getStatusCodeValue()==200){
                 ...
            }
               ...
    
        }
    }
    
    @RestController
    Class XYZ{
       
       @PostMapping("/get-data")
       ResponseEntity<Object> getTheStatus(@RequestHeader HttpHeaders headers ,@ResponseBody MyData data){
    
              return new ResponseEntity<>("",HttpStatus.BAD_REQUEST);
    
       }
    
    }

In HTTP context response status 200 represent success response. Statuses 4xx and 5xx represent some problems. The problem can be related to a request, connection, server, or another source. Some HTTP client implementations like RestTemplate will throw exceptions in case of non-success status code because non-success response status represents failed execution .

If you want to avoid exceptions you can add an error handler.

public class RestTemplateResponseErrorHandler 
  implements ResponseErrorHandler {

    @Override
    public boolean hasError(ClientHttpResponse httpResponse) throws IOException {
      return false;
    }

    @Override
    public void handleError(ClientHttpResponse httpResponse) throws IOException {}
}

RestTemplate restTemplate = restTemplateBuilder
          .errorHandler(new RestTemplateResponseErrorHandler())
          .build();

template.postForEntity("http://localhost:8090/get-data", body, String.class);

it's happen because of passing HttpStatus.BAD_REQUEST

IMHO returning 4xx statuses like this isn't the best way, use @ControllerAdvice instead

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM