Handle Webclient async calls exceptions for non REST calls

162 Views Asked by At

I am calling Spring webclient as follows and get Mono response (async). Please notice that the call is not blocked. I invoke this in a scheduled job, so this async call is not initiated by a REST call. Problem is when exception occurred, it will be thrown and print the whole stack trace (I want to avoid that). I just want to catch the exceptions and log it more elegantly. We cannot put the logic around try/catch clause because this is a Mono call. Also I have seen how to catch exceptions globally for webclient async calls, but then it has to be invoked via REST call. Using AOP is not a solution either as this is a async mono call. So how do I capture the exceptions and handle them?

var monoVersionReply = webClient.post().uri(versionInfoApi)
            .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
            .retrieve()
            .onStatus(HttpStatus::isError, response -> {
                if (response.statusCode().is4xxClientError()) {
                    logger.error("4xx client error: " + response.statusCode() + ", message:" + response);
                } else {
                    logger.error("server error error: " + response.statusCode() + ", message:" + response);
                }
                return Mono.error(new RemoteApiCallException("service response code is not 200: " + response.statusCode()));
            })
            .bodyToMono(String.class)
            .onErrorMap(Predicate.not(RemoteApiCallException.class::isInstance), throwable -> new RemoteApiCallException(throwable.getMessage()))
            .doOnError(e -> logAllErrors(e));

monoVersionReply.subscribe(reply -> handleGetVersionResponse(reply));

At line 10, return Mono.error(exception) is the one I want to catch and handle. doOnError() is working fine and handled properly.

0

There are 0 best solutions below