Feign & Error Decoder

알파로그·2023년 10월 13일
0

✏️ Error Decoder

📍 외부 요청 예외처리

  • feign 을 사용하면 편리하게 외부 api 에 요청과 응답을 받을 수 있다.
    • 하지만 내부에서 컨트롤 할 수 없는 외부환경으로의 요청이기 때문에 항상 오류가 발생할 가능성을 염두해야 하고,
      오류처리를 필수로 해줘야 한다.
    • Error Decoder 를 사용하면 깔끔하고 편리하게 오류처리를 할 수 있다.

📍 Feign Exception 하위 예외

  • feign 은 자체적으로 Exception 이 존재하고 400 번과 500번으로 나눠서 세세하게 오류가 관리되고 있다.
    • Fegin Client Exception
      • 400 번 때 오류
    • Fegin server Exception
      • 500 번 때 오류
  • 하지만 특정 client 객체에서 특정 오류를 별도로 관리하고 싶을 때 Error Decoder 를 사용해 구체적으로 커스텀 할 수 있다.

✏️ 적용하기

📍 FeignErrorDecoder 객체 생성

  • switch 문을 사용해 직접 커스텀 할 수 있음
    • 각 오류를 한번 더 별도로 생성해 원하는 Exception 이 발생하도록 설정할 수 있음
import com.baeker.member.base.error.exception.NotFoundException;
import feign.Response;
import feign.codec.ErrorDecoder;
import jakarta.ws.rs.InternalServerErrorException;

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

        switch (response.status()) {
            case 400 :
                return new NotFoundException("feign: data 를 찾을 수 없습니다.");
            case  500 :
                return new InternalServerErrorException("서버 내부에 오류가 발생했습니다.");
        }
        return new Exception(response.reason());
    }
}

📍 Been 등록

  • 생성한 Error Decode 객체를 Bean 으로 등록한다
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class FeignConfiguration {

    @Bean
    public FeignErrorDecoder feignErrorDecoder() {
        return new FeignErrorDecoder();
    }
}

📍 Feign Client 에 적용

  • 속성값으로 명시해주면 커스텀한 Error Decode 객체를 사용할 수 있다.
import org.springframework.cloud.openfeign.FeignClient;

@FeignClient(name = "", url = "", configuration = FeignConfiguration.class)
public interface SolvedAcClient {

		...
}
profile
잘못된 내용 PR 환영

0개의 댓글