I'm using spring-webflux
to call an external webservice async, like:
String param1;
int param2;
webClient.send(...)
.exchange()
.doOnSuccess(rsp -> processResponse(rsp))
.onErrorMap(ex -> processException(ex, param1, param2));
Now I want to refactor the actual sending into a more generic method, and the caller should provide the success + error functions a parameters. But how?
public Mono send(Function success, Function error) {
return webClient.send(...)
.exchange()
.doOnSuccess(success)
.onErrorMap(error);
}
Question: how can I now pass the functions to my generic method?
It must be similar to the following pseudo code, but how exactly do I have to write the functions?
public void caller() {
String param1;
int param2;
send(
rsp -> processResponse(rsp),
ex -> processException(ex, param1, param2)
);
}
If you definitely want to use onErrorMap()
(to map one exception to another) then:
public Mono<ClientResponse> send(Consumer<? super ClientResponse> success, Function<? super Throwable, ? extends Throwable> error) {
return webClient()
.get()
.uri("http://example.com/")
.exchange()
.doOnSuccess(success)
.onErrorMap(error);
}
send(cr -> processResponse(cr), ex -> mapToAnotherException(ex));
...but it sounds like you want to actually add a side-effect on an error, which would be doOnError()
instead:
public Mono<ClientResponse> send(Consumer<? super ClientResponse> success, Consumer<? super Throwable> error) {
return webClient()
.get()
.uri("http://example.com/")
.exchange()
.doOnSuccess(success)
.doOnError(error);
}
send(cr -> processResponse(cr), ex -> processException(ex));
Note however that exchange()
is now deprecated - you'd now normally use exchangeToMono()
instead, supplying a function that returns a Mono<Foo>
from the client response. (If you really want to just return a Mono<ClientResponse>
as before, you could just do .exchangeToMono(Mono::just)
instead though.)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.