Search code examples
javaspringspring-bootresttemplate

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


Solution

  • 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.