Search code examples
springhttp-status-codesspring-rest

Spring http status code - java.lang.IllegalArgumentException: No matching constant


I'm using The spring rest-template for calling the rest URL , I get a response from the server but the http-status code is invalid and the Spring throws , java.lang.IllegalArgumentException: No matching constant . Due to this exception the application is failing , this looks like a bug in the Spring code . Since the http status code received is not in the list spring framework is looking forit failed . Is there a Spring way to handle it ?


Solution

  • Spring seems to use the standard status code in their enum. You can find the status codes here: org.springframework.http.HttpStatus.

    Probably the API you're querying is not returning a standard HTTP Status code. Your best bet is to create a custom error handler, like this:

    var r = new RestTemplate();
    
    r.setErrorHandler(new ResponseErrorHandler() {
      @Override
      public boolean hasError(ClientHttpResponse response) throws IOException {
        return response.getRawStatusCode() != 550;
      }
    
      @Override
      public void handleError(ClientHttpResponse response) {
        // Do nothing?
      }
    });
    
    var response = r.exchange("https://httpbin.org/status/550", HttpMethod.GET, null, String.class);
    
    System.out.println(response.getStatusCodeValue());
    

    What we're saying is basically if the status code returned is 550 (not a standard code), we don't want to do anything about it.

    Another option you have is, of course, to catch the exception and do something about it.

    try {
      // Call the API here
    } catch (IllegalArgumentException e) {
      // Do something about it here...
    }