java - Spring WebClient 根据状态码嵌套 Mono
问题描述
使用 WebClient 我想根据 HTTP 状态码分别处理 ClientResponse。下面你会看到在顶部 doOnSuccess 中使用的两个新的 subscribe() 方法。如何将那些嵌套的 Monos 带到 WebClient 的 Mono 链中?也就是说,如何消除内在的单声道。
webClient.post()
.uri( soapServiceUrl )
.contentType(MediaType.TEXT_XML)
//.body(Mono.just(req), String.class )
.body( Mono.just(getCountryRequest) , GetCountryRequest.class )
.exchange()
.filter( (ClientResponse response) -> { return true; } )
.doOnSuccess( (ClientResponse response) -> {
//nested mono 1
if( response.statusCode().is5xxServerError() ){
response.toEntity(String.class).doOnSuccess(
error -> {
System.out.println("error : "+ error);
}).subscribe();
}
//nested mono 2
if( response.statusCode().is2xxSuccessful() ){
response.toEntity(GetCountryResponse.class).doOnSuccess(
getCountryResponse -> {
System.out.println("success : "+ getCountryResponse.getBody().getCountry().getCapital());
}).subscribe();
}
})
.doOnError( (Throwable error) -> {
System.out.println( "getCountryResponse.error : "+ error );
})
.subscribe();
解决方案
Webclient 的retrieve()
方法有更好的方法来处理错误代码。
我会这样做:
webClient.post()
.uri( soapServiceUrl )
.contentType(MediaType.TEXT_XML)
//.body(Mono.just(req), String.class )
.body( Mono.just(getCountryRequest) , GetCountryRequest.class )
.retrieve()
.onStatus(
HttpStatus::isError,
clientResponse ->
clientResponse
//get the error response body as a string
.bodyToMono(String.class)
//flatmap the errorResponseBody into a new error signal
.flatMap(
errorResponseBody ->
Mono.error(
new ResponseStatusException(
clientResponse.statusCode(),
errorResponseBody))))
//get success response as Mono<GetCountryResponse>
.bodyToMono(GetCountryResponse.class)
.doOnSuccess( (GetCountryResponse response) ->
System.out.println("success : " +
response.getBody().getCountry().getCapital()))
//Response errors will now be logged below
.doOnError(ResponseStatusException.class, error -> {
System.out.println( "getCountryResponse.error : "+ error );
})
.subscribe();
推荐阅读
- javascript - Three.js - 使用平面几何占用所有可用空间(模拟 background-size:cover 属性)
- sql - 多连接成本更低的方式
- swiftui - SwiftUI:在 SwiftUI 中使用 Spacer 垂直对齐动态大小的 Rectangle
- sql - 使用数据类型 varchar 对数字后跟一个字母进行排序
- python - Python,如何跳过循环中的最后一个逗号?
- mongodb - 如何为多个集合创建 mongodb 聚合查询
- vue.js - 在 vuejs 数据对象属性中使用函数参数
- python - 与包含无穷大的元素的矩阵乘法
- python - 如何从 fastq 文件中删除 SeqRecord 对象
- javascript - React.js 使用 Redirect 的简单路由保护