Skip to content

Instantly share code, notes, and snippets.

@mizanRahman
Created January 18, 2016 20:11
Show Gist options
  • Select an option

  • Save mizanRahman/4c5e52225d812194eb76 to your computer and use it in GitHub Desktop.

Select an option

Save mizanRahman/4c5e52225d812194eb76 to your computer and use it in GitHub Desktop.
Api Client
@Getter
public class ApiAccessException extends RuntimeException {
private String status;
private String message;
public ApiAccessException(String message) {
super(message);
}
public ApiAccessException(String status, String message, Throwable cause) {
super(message, cause);
this.message = message;
this.status = status;
}
}
public class JsonUtil {
public static <T> T fromJson(String json, Class<T> tClass) {
try {
return new ObjectMapper().readValue(json, tClass);
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
@Slf4j
public class RestClient {
public <T> T get(String url, Class<T> tClass) {
try {
log.info("request: url {}", url);
ResponseEntity<T> response =
new RestTemplate().getForEntity(url, tClass);
log.info("response={}", response.getBody().toString());
return response.getBody();
} catch (HttpClientErrorException e) {
ErrorResponse errorResponse =
JsonUtil.fromJson(e.getResponseBodyAsString(),
ErrorResponse.class);
log.info("Client error: {}", errorResponse.toString(), e);
ApiAccessException ex
= new ApiAccessException(
errorResponse.getStatus(),
"Api Request Failed: " + errorResponse.getMessage(),
e);
throw ex;
} catch (HttpServerErrorException e) {
log.info("Server error", e);
throw e;
} catch (ResourceAccessException e) {
log.info("Server Down", e);
throw new ServiceUnavailableException("Service is unavailable", e);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment