Created
January 18, 2016 20:11
-
-
Save mizanRahman/4c5e52225d812194eb76 to your computer and use it in GitHub Desktop.
Api Client
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| @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; | |
| } | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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; | |
| } | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| @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