Notice
Recent Posts
Recent Comments
Link
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
Archives
Today
Total
관리 메뉴

개발자되기 프로젝트

[Server] Google Geocoding Error처리 본문

Project/대중교통 길찾기

[Server] Google Geocoding Error처리

Seung__ 2022. 2. 5. 00:48

1. Return값 분석


{
   "results" : [
      {
         "address_components" : [
           ....
         },
         "place_id" : "ChIJ2eUgeAK6j4ARbn5u_wAGqWA",
         "plus_code": {
            "compound_code": "CWC8+W5 Mountain View, California, United States",
            "global_code": "849VCWC8+W5"
         },
         "types" : [ "street_address" ]
      }
   ],
   "status" : "OK"
}

GoogleGeoCoding을 상태값을 바로바로 return한다.

OK OK
ZERO_RESULTS indicates that the geocode was successful but returned no results.
This may occur if the geocoder was passed a non-existent 
address.
OVER_DAILY_LIMIT The API key is missing or invalid.
Billing has not been enabled on your account.
A self-imposed usage cap has been exceeded.
The provided method of payment is no longer valid (for example, a credit card has expired).
OVER_QUERY_LIMIT  indicates that you are over your quota.
REQUEST_DENIED indicates that your request was denied
INVALID_REQUEST generally indicates that the query (address, components or latlng) is missing.
UNKNOWN_ERROR  indicates that the request could not be processed due to a server error. The request may succeed if you try again.

ErrorMessage는 다음과 같은 형태로 return된다.

{
   "error_message" : "The provided API key is invalid. ",
   "results" : [],
   "status" : "REQUEST_DENIED"
}

 

이 중 에서 ZERO_RESULTS는 error_message가 없으며 200으로 정상처리로 된다.

{
   "results" : [],
   "status" : "ZERO_RESULTS"
}

 

또한 Test작성 중  알게되었는데, INVALID_REQUEST의 경우 400을 return한다.

이 부분에 대한 처리도 필요하다.

 

 

2. GoogleClient


HttpStatus 400을 잡아낼 수 있는 로직,

Zero_Result를 처리할 수 있는 로직,

json result에서 status확인 후 return하는 메서드 추가

@Slf4j
@Component
public class GoogleClient {

    @Value("${google.key}")
    private String key;
    @Value(("${google.uri}"))
    private String locationUri;
    private JSONObject jsonResult;

    public void changeKey(String key) {
        this.key = key;
    }

    public JSONObject searchLocation(String location) {
        String status="";

       String uriString = UriComponentsBuilder.fromUriString(locationUri)
               .queryParam("address", location)
               .queryParam("key", key).build().toUriString();

       URI uri = UriComponentsBuilder.fromUriString(uriString).build().toUri();

       log.info("[request google api] uri = {}", uri);
       //Http Entity
       var httpEntity = new HttpEntity<>(new HttpHeaders());
       var responseType = new ParameterizedTypeReference<String>(){};

        try{
            //ResponseEntity
            var responseEntity= new RestTemplate().exchange(
                    uri, HttpMethod.GET, httpEntity, responseType
            );
            jsonResult = new JSONObject(responseEntity.getBody());
            status = (String) jsonResult.get("status");
            if (!status.equals("OK")){
                errorCheck(jsonResult, status);
            }
        }catch (HttpClientErrorException.BadRequest | HttpServerErrorException.InternalServerError exception){
            log.info("[Google Client] Exception 발생: {}", exception.getMessage());
            JSONObject errorInfo = new JSONObject(exception.getResponseBodyAsString());
            errorCheck(errorInfo, exception.getStatusCode().name());
        }

        return jsonResult;

    }

    private void errorCheck(JSONObject jsonResult, String status) {
        if ( status.equals("UNKNOWN_ERROR")){
            String errorMessage = (String) jsonResult.get("error_message");
            log.info("[Google Client Error] Status: {}", status);
            log.info("[Google Client Error] errorMessage: {}", errorMessage);
            throw new IllegalStateException(errorMessage);
        }else if (status.equals("ZERO_RESULTS")){
            log.info("[Google Client Error] Status: {}", status);
            throw new NoResultException("결과가 없습니다.");
        } else {
            String errorMessage = (String) jsonResult.get("error_message");
            log.info("[Google Client Error] Status: {}", status);
            log.info("[Google Client Error] errorMessage: {}", errorMessage);
            throw new IllegalArgumentException(errorMessage);
        }
    }
}

참고로 try구문 실행 중 400이나 500에러가 바생하면 바로 catch로 넘어간다. 

 

이 때 ResponseBody의 data는 Exception에 담겨있다.

 

Exception.getResponseBodyAsString()으로 사용이 가능하다. 

 

3. Test


@SpringBootTest
class GoogleClientTest {
    @Value("${google.key}")
    private String key;

    @Autowired
    GoogleClient googleClient;

    @AfterEach
    void rollbackKey(){
        googleClient.changeKey(key);
    }

    @Test
    @DisplayName("send wrong key")
    void wrongKey(){
        googleClient.changeKey("wrong Key");
        Assertions.assertThrows(IllegalArgumentException.class, () ->{googleClient.searchLocation("서울역");});
    }

    @Test
    @DisplayName("No Result")
    void noResult(){
        Assertions.assertThrows(NoResultException.class, () ->{googleClient.searchLocation("a5dsQ2");});
    }

    @Test
    @DisplayName("empty data")
    void emptyData(){
        Assertions.assertThrows(IllegalArgumentException.class, () ->{googleClient.searchLocation("");});
    }
}

 

 

4. GitHub: 220205 GoogleGeocoding ErrorMessage


 

GitHub - bsh6463/commuteMap

Contribute to bsh6463/commuteMap development by creating an account on GitHub.

github.com

 

'Project > 대중교통 길찾기' 카테고리의 다른 글

Field값 검증  (0) 2022.02.07
[Server] Exception Resolver  (0) 2022.02.05
[Server] Oday Error 처리2  (0) 2022.02.04
[Server] Oday Error 처리  (0) 2022.02.03
[Server] 단일책임 원칙  (0) 2022.02.01
Comments