본문 바로가기
IT 자료

restTemplate.exchange 예외처리

by 성곤 2022. 2. 14.
반응형

 

restTemplate.exchange 예외처리

 

restTemplate.exchange의 경우 400, 500의 응답코드를 받으면 에러로 뱉는다
이 때, BODY를 가져오는 방법은 예외처리를 통해서 가져올 수 있다. (getResponseBodyAsString)

 


// 예외처리 import
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.HttpServerErrorException;

@Autowired
RestTemplate restTemplate;
	
public Map callRestAPI(Map<String, Object> paramters, String url) throws Exception {
	
	Map responseResult = null;
	
	// 헤더 정보가 있는 경우
	String apiKey = "apiKey";
	HttpHeaders headers = HeaderUtil.getHeadersWithAPIM();
	headers.add(HeaderConstants.APIKEY, apiKey);
	HttpEntity<Map<String, Object>> request = new HttpEntity<>(paramters, headers);


	URI uri = new URI(url);

	// 수정 전 API 호출 코드
	// ResponseEntity<Map> responseEntity = restTemplate.exchange(uri, HttpMethod.POST, request, Map.class);

	ResponseEntity<Map> responseEntity = null;

	// 수정 후 API 예외처리
	try{
		responseEntity = restTemplate.exchange(uri, HttpMethod.POST, request, Map.class);

	}catch(HttpClientErrorException e) {

		LOG.info("HttpClientErrorException : " + String.valueOf(e.getResponseBodyAsString()));
		throw new Exception(String.valueOf(e.getResponseBodyAsString()));

	}catch(HttpServerErrorException e) {

		LOG.info("HttpServerErrorException : " + String.valueOf(e.getResponseBodyAsString()));
		throw new Exception(String.valueOf(e.getResponseBodyAsString()));

	}catch(Exception e) {

		LOG.info("Exception : " + String.valueOf(e.getStackTrace()));
		throw new Exception(String.valueOf(e.getStackTrace()));
	}

	if (responseEntity.getBody() != null) {
		responseResult = responseEntity.getBody();
	}
	return responseResult;
}

 

 

출처 : https://stackoverflow.com/questions/56336439/resttemplate-throwing-generic-400-bad-request-but-custom-server-sent-message-is/56336951

반응형