Skip to content

Commit ac43355

Browse files
committed
feat: RestTemplate용 ResponseErrorHandler 및 설정 클래스 추가
1 parent 82b3e2c commit ac43355

File tree

2 files changed

+52
-0
lines changed

2 files changed

+52
-0
lines changed
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
package com.example.log4u.common.external;
2+
3+
import org.springframework.context.annotation.Bean;
4+
import org.springframework.context.annotation.Configuration;
5+
import org.springframework.web.client.RestTemplate;
6+
7+
import com.example.log4u.common.external.hanlder.ApiResponseErrorHandler;
8+
9+
@Configuration
10+
public class ClientConfig {
11+
12+
@Bean
13+
public RestTemplate restTemplate() {
14+
RestTemplate restTemplate = new RestTemplate();
15+
restTemplate.setErrorHandler(new ApiResponseErrorHandler());
16+
return restTemplate;
17+
}
18+
}
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
package com.example.log4u.common.external.hanlder;
2+
3+
import java.io.BufferedReader;
4+
import java.io.IOException;
5+
import java.io.InputStreamReader;
6+
import java.util.stream.Collectors;
7+
8+
import org.springframework.http.client.ClientHttpResponse;
9+
import org.springframework.web.client.ResponseErrorHandler;
10+
11+
import com.example.log4u.common.external.exception.ExternalApiRequestException;
12+
13+
import lombok.extern.slf4j.Slf4j;
14+
15+
@Slf4j
16+
public class ApiResponseErrorHandler implements ResponseErrorHandler {
17+
@Override
18+
public boolean hasError(ClientHttpResponse response) throws IOException {
19+
return !response.getStatusCode().is2xxSuccessful();
20+
}
21+
22+
@Override
23+
public void handleError(ClientHttpResponse response) throws IOException {
24+
String body;
25+
try (BufferedReader reader = new BufferedReader(new InputStreamReader(response.getBody()))) {
26+
body = reader.lines().collect(Collectors.joining("\n"));
27+
}
28+
29+
log.error("API 호출 중 에러 발생: HTTP 상태 코드: {}, 응답 본문: {}", response.getStatusCode().value(), body);
30+
31+
throw new ExternalApiRequestException(response.getStatusCode().toString(),
32+
"API 호출 중 에러 발생: " + response.getStatusCode().value() + " 응답 본문: " + body);
33+
}
34+
}

0 commit comments

Comments
 (0)