【发布时间】:2020-01-01 02:49:13
【问题描述】:
我使用此代码发送 XML 请求:
RestClient client = RestClientBuilder.builder()
.gatewayUrl(URL)
.build();
Mono<AuthorizeResponse> result = client.executeAndReceiveAuthorize(request);
response = result.block();
public RestClient(String gatewayUrl, String token, String username, String password, SslContext sslContext) {
this.token = token;
this.gatewayUrl = gatewayUrl;
WebClient.Builder builder = WebClient.builder().baseUrl(gatewayUrl);
if (sslContext != null) {
HttpClient httpClient = HttpClient.create().secure(sslContextSpec -> sslContextSpec.sslContext(sslContext));
ClientHttpConnector httpConnector = new ReactorClientHttpConnector(httpClient);
builder.clientConnector(httpConnector);
}
if (username != null && password != null) {
builder.filter(basicAuthentication(username, password));
}
client = builder.build();
}
public Mono<AuthorizeResponse> executeAndReceiveAuthorize(AuthorizeRequest transaction) {
Mono<AuthorizeRequest> transactionMono = Mono.just(transaction);
return client.post().uri(checkTrailingSlash(gatewayUrl) + token)
.header(HttpHeaders.USER_AGENT, "Mozilla/5.0")
.accept(MediaType.APPLICATION_XML)
.contentType(MediaType.APPLICATION_XML)
.body(transactionMono, AuthorizeRequest.class)
.retrieve()
.bodyToMono(AuthorizeResponse.class);
}
但有时我会收到此错误:
org.springframework.web.reactive.function.client.WebClientResponseException$Unauthorized: 401 Unauthorized
at java.base/java.lang.Thread.run(Thread.java:834)
2019-08-27 22:05:45,720 ERROR [stderr] (processingTransactionGenesisAuthorizeContainer-1) Suppressed: java.lang.Exception: #block terminated with an error
Caused by: java.lang.NullPointerException: null
当我收到错误 401 时如何捕获和处理异常?
如果可能的话,我想在response = result.block(); 行之后处理异常。
【问题讨论】:
-
您是否尝试过对
Mono使用onError处理程序?
标签: java spring spring-boot spring-webflux