WebClient
素人です。
以前のRestTemplate
では以下ですべてのHttpStatus
に対して例外をスローしなくなる。
RestTemplate client = builder.errorHandler(new ResponseErrorHandler() {
@Override
public boolean hasError(ClientHttpResponse response) throws IOException {
return false;
}
@Override
public void handleError(ClientHttpResponse response) throws IOException {
}
}).build();
これと同じ事をWebClient
をしたい……が、パっと見ではRestTemplate
と同じやり方では出来ない、ように見えた。そこで https://gist.github.com/abhi2495/4607f2c827b2130ab6e08320f4ca5079 によると、@ExceptionHandler
を使うやり方が紹介されている。
id 'org.springframework.boot' version '2.6.7'
以下は、status code, header, bodyをそのまま返している。
@ExceptionHandler(value = WebClientResponseException.class)
public ResponseEntity<String> handleWebClientException(WebClientResponseException ex) {
return ResponseEntity
.status(ex.getStatusCode())
.headers(ex.getHeaders())
.body(ex.getResponseBodyAsString());
}