back-end/spring boot

Spring WebClient 응답 및 예외 처리

study-minjeong 2024. 3. 28. 14:30

retrieve를 사용한 요청 방법과 Exception handling 방법을 정리한 내용입니다!

 

 

WebClient로부터 응답을 받을 때는 retrieve(), exchange() 둘 중 하나를 선택해서 사용하면 됩니다.

retrieve() : body를 받아 디코딩하는 간단한 메소드

exchange() : 상태값, 헤더, response를 함께 가져오는 메소드

exchange()를 사용하면 세세한 컨트롤이 가능하지만, 메모리 누수 가능성이 있기 때문에 retrieve()를 권고한다고 합니다.

 

 

 

retrieve()를 사용한 후 데이터를 2가지 형태로 받을 수 있습니다.

1. toEntity()

status, headers, body를 포함하는 ResponseEntity 타입으로 받을 수 있습니다.

 Mono<ResponseEntity<Result>> entityMono = client.get()
     .uri("/uri")
     .accept(MediaType.APPLICATION_JSON)
     .retrieve()
     .toEntity(Result.class);

 

 

2. toFlux(), toMono()

받은 응답을 bodyToFlux, bodyToMono를 이용하여 Flux, Mono 객체로 바꿔줍니다. 

Mono 객체는 0-1개의 결과를 처리하는 객체이고, Flux는 0-N개의 결과를 처리하는 객체입니다.

response body를 원하는 타입으로 받게 해줍니다. 객체 스트림으로도 디코딩할 수 있습니다.

Mono<Result> result = client.get()
    .uri("/uri")
    .accept(MediaType.APPLICATION_JSON)	// MediaType 설정
    .retrieve()	// 받은 응답 디코딩
    .bodyToMono(Result.class);

 

 

 

 

그리고 onStatus를 이용하여 응답 상태 코드 별로 다음과 같이 처리할 수 있습니다.

Mono<Result> result = client.get()
        .uri("/uri").accept(MediaType.APPLICATION_JSON)
        .retrieve()
        .onStatus(HttpStatus::is4xxClientError, response -> ...)
        .onStatus(HttpStatus::is5xxServerError, response -> ...)
        .bodyToMono(String.class);

 

응답 세부 메시지를 뽑아낼 수 있는 방법입니다.

.onStatus(HttpStatus::isError, response -> {
     response.bodyToMono(Exception.class).map(body -> new RuntimeException(body.getMessage()))
})