-
Notifications
You must be signed in to change notification settings - Fork 2
FeignClient ErrorDecoder @RestControllerAdvice 사용
injongjeon edited this page Mar 25, 2025
·
1 revision
try {
slackClient.sendMessage(request);
} catch (Exception e) {
// 상태코드별 처리
}
문제상황: FeignClient를 사용할 때, HTTP 응답 코드에 따라 직접 예외를 분기 처리해야 했다.
그로 인해 FeignClient 호출부마다 try-catch 블록이 반복적으로 사용되었고, 코드가 지저분하고 유지보수에 어려움이 있었다.
@Component
public class SlackClientErrorDecoder implements ErrorDecoder {
private final ErrorDecoder defaultDecoder = new Default();
@Override
public Exception decode(String methodKey, Response response) {
if (response.status() >= 400 && response.status() <= 499) {
return new HubException.SlackServerErrorException("요청 데이터가 올바르지 않습니다.");
} else if (response.status() >= 500) {
return new HubException.SlackServerErrorException("슬랙 서버에 문제가 발생했습니다.");
}
return defaultDecoder.decode(methodKey, response);
}
}
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(HubException.SlackServerErrorException.class)
public ResponseEntity<ErrorResponse> handleSlackError(HubException.SlackServerErrorException e) {
return ResponseEntity.status(HttpStatus.BAD_GATEWAY)
.body(new ErrorResponse("슬랙 전송 실패", e.getMessage()));
}
}
해결방안: ErrorDecoder를 이용해서 호출하는 부분에서는 예외를 처리하는 부분은 제거를 할 수 있었고 @RestControllerAdvice에서 이 예외를 처리하게끔 함으로써
코드를 깔끔하게 작성할 수 있었다.