Blog

Spring Framework 5.2 からは WebClient の retrieve でちゃんと http status を取れる

Spring Framework 5.2 がリリースされた。

Support for Kotlin Coroutines.

も大きいのだが、、個人的には以下に注目したい。

Refinements to WebClient API to make the retrieve() method useful for most common cases, specifically adding the ability to retrieve status and headers and addition to the body. The exchange() method is only for genuinely advanced cases, and when using it, applications can now rely on ClientResponse#createException to simplify selective handling of exceptions.

これまで、Webclient を利用した場合、.retreive().bodyToMono(String.class) などとして response body のみを取得するメソッドしかなく、異常に使いづらかった。 HTTP Status Code が 2xx 以外の場合には例外が上がる設計になっているのはいいのだが、現実的にはどの HTTP Status Code かは例外ではなく通常の処理としてハンドリングしたいというケースも多いのである。

Spring Framework 5.2 以後では以下のように記述可能になった。

        WebClient client = WebClient.create();
        Mono<ResponseEntity<String>> responseEntityMono = client.get()
                                                                .uri(url)
                                                                .retrieve()
                                                                .toEntity(String.class);

        ResponseEntity<String> responseEntity = responseEntityMono.block();
        assert responseEntity != null;
        log.info("url={} status={} headers={} body={}",
                 url,
                 responseEntity.getStatusCodeValue(),
                 responseEntity.getHeaders(),
                 responseEntity.getBody());

便利。