ABOUT ME

진심은 있으되 진심밖에 없는 태도는 취하지 말고, 불확실한 삶에서 내가 내릴 수 있는 가장 자유로운 선택은 오늘 하루를 행복하게 사는 것:)

  • Feign Client 구현 - 4
    [공부] 프로그래밍/Spring・Spring Boot (JAVA) 2024. 5. 22. 11:19

     
    ♧ 전체 코드 : https://github.com/woodisco/feign-client

    GitHub - woodisco/feign-client: feign-client 공부

    feign-client 공부. Contribute to woodisco/feign-client development by creating an account on GitHub.

    github.com

     

    ErrorDecoder 구현

    요청에 대해 정상 응답이 아닌 경우, 핸들링이 가능하다.
    ① DemoController 수정

    @GetMapping("/error")
    public String errorDecoderController() {
        return demoService.errorDecoder();
    }

    ② DemoService 수정

    public String errorDecoder() {
        demoFeignClient.callErrorDecoder();
        return "errorDecoder";
    }

    ③ DemoFeignClient 수정

    @GetMapping("/errorDecoder")
    ResponseEntity<BaseResponseInfo> callErrorDecoder();

    ④ TargetController 수정

    @GetMapping("/errorDecoder")
    public ResponseEntity<BaseResponseInfo> testErrorDecoder() {
        return ResponseEntity.status(HttpStatus.NOT_FOUND).build();
    }

    ⑤ DemoFeignErrorDecoder 작성
    : ErrorDecoder를 이용해 해당 에러의 핸들링을 정의한다.

    public class DemoFeignErrorDecoder implements ErrorDecoder {
    
        private final ErrorDecoder errorDecoder = new Default();
    
        @Override
        public Exception decode(String methodKey, Response response) {
            final HttpStatus httpStatus = HttpStatus.resolve(response.status());
    
            /**
             * 외부 컴포넌트와 통신 시
             * 정의해놓은 예외 코드 일 경우엔 적절하게 핸들링하여 처리한다.
             */
            if (httpStatus == HttpStatus.NOT_FOUND) {
                System.out.println("[DemoFeignErrorDecoder] Http Status = " + httpStatus);
                throw new RuntimeException(String.format("[RuntimeException] Http Status is %s", httpStatus));
            }
    
            return errorDecoder.decode(methodKey, response);
        }
    }
    ▷ HttpStatus.resolve(response.status()) :
    HTTP 상태 코드(int)를 받아서 해당 코드에 대응하는 HttpStatus 열거형(enum) 값을 반환한다. 만약 주어진 코드에 해당하는
    HttpStatus 값이 없으면, null을 반환한다. 

    ▷ errorDecoder.decode(methodKey, response) :
    위에서 처리되지 않은 예외는 기본 ErrorDecoder로 위임하여 처리한다. Default 인스턴스의 decode 메서드를 호출하여 기본 오류 처리 로직을 따르게 한다.

    ⑥ DemoFeignConfig 수정
    : DemoFeignErrorDecoder를 Bean으로 등록하기.

    @Bean
    public DemoFeignErrorDecoder DemoErrorDecoder() {
        return new DemoFeignErrorDecoder();
    }

     

    출처 : 패스트캠퍼스 10개 프로젝트로 완성하는 백엔드 웹개발(Java/Spring) 초격차 패키지 Online

    '[공부] 프로그래밍 > Spring・Spring Boot (JAVA)' 카테고리의 다른 글

    Logback 구현 - 2  (0) 2024.05.23
    Logback 구현 - 1  (0) 2024.05.22
    Feign Client 구현 - 3  (0) 2024.05.22
    Feign Client 구현 - 2  (0) 2024.05.21
    Feign Client 구현 - 1  (0) 2024.05.21
Designed by Tistory.