관리 메뉴

IT.FARMER

open feign error decoder custom 본문

Spring/Spring Cloud

open feign error decoder custom

아이티.파머 2022. 1. 14. 11:35
반응형

오픈페인을 사용하면서 발생되는 오류에 대한 컨트롤을 커스텀 하게 구현 할 수 있다.

ErrorDecoder 를 상속받아 구현하면 된다. HTTP method 에 따라 응답값을 확인하고 익셉션을 다르게 설정 한다. 만약 circuit breaker 기능중 retry 기능을 사용하기 위해서는 exception 을 꼭 RetryableException을 사용하여야 한다. 다른 익셉션을 던지면 retry 는 설정해도 동작 되지 않는다.

@Slf4j
public class GlobalCustomErrorDecoder implements ErrorDecoder {
    @Override
    public Exception decode(String methodKey, Response response) {

        log.warn("global error code {}", response.status());
        switch (response.status()){
            case 400:
                return new BadRequestException(HttpStatus.valueOf(response.status()));
            case 404:
                return new NotFoundException(HttpStatus.valueOf(response.status()));
            case 500:
                return new InternalServerException(HttpStatus.valueOf(response.status()));
            case 501:
            case 502:
            case 503:
                return new RetryableException(response.status(),response.reason(), response.request().httpMethod(), null,response.request());
        }
        return new Default().decode(methodKey, response);
    }
}

페인을 사용하는 모든 클라이언트에 디코더를 정의하기 위해 application.yml 에 default 로 등록해 준다.

혹은 @FeignClient(config={}) 에 customer config로 사용할 class 를 등록해준다.

feign:
  client:
    config:
      default:
        errorDecoder: com.client.config.GlobalCustomErrorDecoder
        connectionTimeout: 3000
        readTimeout: 3000
    default-to-properties: false

default-to-properties 는 기본 true 로 프로퍼티에 있는 값을 기본으로 사용한다. @FeignClient를 통해 클레스의 우선순위를 높게 하고 싶다면 false 로 주고 사용한다.

@FeignClient(
        name="MOS-SERVICE-PRODUCT"
        , configuration = {GlobalCustomFeignConfig.class, ProductErrorDecoder.class}
        , fallback = ProductApiFeignEurekaClient.ProductFallback.class
)
반응형