ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • FeignClient Response로 Http status 제어하기
    Spring Framework 2023. 12. 1. 00:01

    개요

    FeignClient를 다루다 보면 200~300번대가 아닌 상태코드에 대하여 ErrorHandling을 수행해야 할 경우가 있습니다.

    하지만 ErrorDecoder에 의해 FeignClient Exception이 발생하곤 하는데 이에 대해서 대응하는 방법을 찾아보고자 합니다.

     

    Response객체

    public final class Response implements Closeable {
    
      private final int status;
      private final String reason;
      private final Map<String, Collection<String>> headers;
      private final Body body;
      private final Request request;
      private final ProtocolVersion protocolVersion;
      
      ...
    }

    return Type으로 Response 객체를 받으면 예외 없이 http 호출 결과를 반환받을 수 있습니다.

    status, body등에 대한 정보를 파악할 수 있습니다.

     

    호출부

    @FeignClient(
        name = "localTestFeign",
        url = "http://localhost:8080",
    )
    interface LocalFeignClient {
        @GetMapping("/internal-call")
        fun getProfiles(): Response
    
        @GetMapping("/internal-call-return-404")
        fun get404(): Response
    
        @GetMapping("/internal-call-return-400")
        fun get400(): Response
    }

    404, 400, body에 대한 반환값을 모두 Response로 받습니다.

     

     

    호출 예시

    HTTP/1.1 404
    connection: keep-alive
    content-length: 0
    date: Tue, 14 Nov 2023 16:07:52 GMT
    keep-alive: timeout=60
    
    HTTP/1.1 400
    connection: close
    content-length: 0
    date: Tue, 14 Nov 2023 16:07:52 GMT
    
    HTTP/1.1 200
    connection: keep-alive
    content-type: application/json
    date: Tue, 14 Nov 2023 16:07:58 GMT
    keep-alive: timeout=60
    transfer-encoding: chunked
    
    feign.Response$InputStreamBody@23d05182

     

     

    Body에 대한 파싱

        @GetMapping("/outer-call")
        fun `외부 호출용 메서드`(){
            val  response = localFeignClient.getProfiles()
            val objectMapper = ObjectMapper()
            objectMapper.registerModule(kotlinModule())
            val responseBody = objectMapper.readValue(response.body().asInputStream(), ClientProfileResponse::class.java)
            println(responseBody)
        }

    objectMapper를 등록하고 Response객체의 body값의 inputStream을 objectMapper를 통해 파싱 합니다. 

     

    호출결과

    ClientProfileResponse(profiles=[Profile(col1=1)])

     

     

    마무리

    Response객체를 활용하면 Body값을 파싱해야하는 불편함이 있지만 Http status code를 직접적으로 예외 없이 핸들링 할 수 있습니다.

     

    댓글

Designed by Tistory.