abn
abn

Reputation: 61

Rest template result is getting null in api call in spring boot

I am using below code to call remote API to remove user id(http://localhost:8080/remove).

try {
final RestTemplate restTemplate = new RestTemplate();
    final UriComponentsBuilder builder = 
UriComponentsBuilder.fromUriString(url);
    builder.queryParam("acdc_id", acdcId);
ResponseEntity<ServiceResponse> result =
            restTemplate.exchange(
                builder.toUriString(),
                HttpMethod.DELETE,
                null,
                ServiceResponse.class);
}catch(Exception e){
//exception handling
}

Remote API return 200 http code for success flow(working fine), but when some user id will not available then API sent below custom response:

{
"error code": "404",
"error": "USER ID Node not found : xyz"
} 

I have already ServiceResponse.java class to get above response, but Rest Template returning below error in this case.

org.springframework.web.client.HttpClientErrorException$NotFound: 404 null
at org.springframework.web.client.HttpClientErrorException.create(HttpClientErrorException.java:85)
at org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:122)
at org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:102)
at org.springframework.web.client.ResponseErrorHandler.handleError(ResponseErrorHandler.java:63)
at org.springframework.web.client.RestTemplate.handleResponse(RestTemplate.java:778)
at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:736)
at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:670)
at org.springframework.web.client.RestTemplate.exchange(RestTemplate.java:579) 

My ServiceResponse class is,

@JsonIgnoreProperties(ignoreUnknown = true)
public class ServiceResponse {

@JsonProperty(value = "error code")
private String errorCode;

@JsonProperty(value = "error")
private String error;

/**
 * @return the error.
 */
public String getError() {
    return error;
}

/**
 * @param error The error to set.
 */
public void setError(final String error) {
    this.error = error;
}

/**
 * @return the errorCode.
 */
public String getErrorCode() {
    return errorCode;
}

/**
 * @param errorCode The errorCode to set.
 */
public void setErrorCode(final String errorCode) {
    this.errorCode = errorCode;
}

}

Could you please help me here to fix my issue, or provide any suggestion, how I can get proper response from API instead null error

Upvotes: 1

Views: 6578

Answers (2)

dassum
dassum

Reputation: 5103

You can use Controller Advice @ControllerAdvice annotation to handle the exceptions . You can send Custom response from the method. You can define exceptionHandler for HttpClientErrorException and send custom response from this method.

Please check https://www.tutorialspoint.com/spring_boot/spring_boot_exception_handling.htm for further details.

One more option is you can use CustomResponseErrorHandler something like below

@Component
public class RestTemplateResponseErrorHandler 
  implements ResponseErrorHandler {

    @Override
    public boolean hasError(ClientHttpResponse httpResponse) 
      throws IOException {

        return (
          httpResponse.getStatusCode().series() == CLIENT_ERROR 
          || httpResponse.getStatusCode().series() == SERVER_ERROR);
    }

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

        if (httpResponse.getStatusCode()
          .series() == HttpStatus.Series.SERVER_ERROR) {
            // handle SERVER_ERROR
        } else if (httpResponse.getStatusCode()
          .series() == HttpStatus.Series.CLIENT_ERROR) {
            // handle CLIENT_ERROR
            if (httpResponse.getStatusCode() == HttpStatus.NOT_FOUND) {
                throw new NotFoundException();
            }
        }
    }
}

And then use it like

@Bean
    RestTemplate restTemplate() {
        RestTemplate restTemplate = new RestTemplate();
        restTemplate.setErrorHandler(new RestTemplateResponseErrorHandler());

        return restTemplate;
    }

Please check https://www.baeldung.com/spring-rest-template-error-handling for ResponseErrorHandler

Upvotes: 0

prakashb
prakashb

Reputation: 170

As I mentioned in the comment, you're getting HttpClientErrorException, which should be caught and dealt with. You're catching the whole Exception class, but there is no code in it. Or you can use @ControllerAdvice and @ExceptionHandler together to achieve this as well.

Upvotes: 1

Related Questions