(Reactive)FeignClient Exception Handling

조갱·2022년 9월 17일
2

이슈 해결

목록 보기
3/14

가는 말은 고왔는데, 오는 말은...

개인 프로젝트 진행중에, ReactiveFeignClient (이하 FeignClient) 의 Exception을 핸들링해야 하는 상황이 생겼다.

FeignClient를 통해 Request를 날렸는데, 응답은 401을 받았지만 500에러를 뱉은 것.

/*****************************************
 *   UPBIT 입금
 ****************************************/
@PostMapping("/deposits/krw", consumes = ["application/json"])
fun depositKRW(
    @RequestParam(value = "amount") amount: Double
): Mono<UpbitDepositKRWResponse>

FeignClient는 위와 같이 작성했고, 뱉은 에러는 아래와 같다.

3rd party app에서 뱉은 에러코드를 동일하게 출력해주도록 한다.

Configuration 수정

ErrorDecoder Bean 등록

@Configuration
@EnableReactiveFeignClients(basePackages = ["{FEIGN CLIENT 패키지 경로}"])
class FeignClientConfiguration {
    @Bean
    fun errorDecoder(): ErrorDecoder {
        return FeignClientErrorDecoder()
    }
    
	//... (개인적인 configuration)
}

에러가 발생하면 연결할 Decoder를 Bean으로 등록한다.

Decoder 코드 작성

class FeignClientErrorDecoder : ErrorDecoder {
    override fun decode(methodKey: String, response: Response): Exception {
        return ErrorDecoder.Default().decode(methodKey, response)
    }
}

return 문에 BreakPoint 를 걸고 디버깅을 찍어보면

위 사진과 같이 response변수를 통해 에러 코드와 메시지를 얻을 수 있다.

Error Message Body 얻기

에러 메시지 본문은 response.body() 에서 byte[] 형태로 갖고있기 때문에
String(response.body().asInputStream().readAllBytes())
위 코드를 통해 에러메시지를 얻을 수 있다.

(더 정확히는 respose.body() 는 feign.Response$ByteArrayBody 타입이기 때문에 asInputStream().readAllBytes()를 통해 byte Array를 얻는다.)

뒷 일을 부탁해!

뒷 일은 각자 Exception Handler 를 구현하여 잘 해결하길 바란다..

Reference :
https://velog.io/@hanqyu/Spring-OpenFeign-%EC%97%90%EB%9F%AC%EC%97%90-%EB%8D%94-%EB%A7%8E%EC%9D%80-%EC%A0%95%EB%B3%B4-%EB%8B%B4%EA%B8%B0-ErrorDecoder

profile
A fast learner.

0개의 댓글