如何解决Spring WebClient 奇怪的行为
我正在使用 webClient
使用以下代码执行 http 请求
@Bean
public CommandLineRunner commandLineRunner() {
return args -> Flux.just(1)
.flatMap(__ -> WebClient
.builder()
.build()
.post()
.uri("http://thisuridoesnotexist/")
.exchangetoMono(response -> Mono.just(1))
.doOnError(throwable -> System.out.println("1"))
.onErrorResume(
Exception.class,throwable -> {
System.out.println("2");
return Mono.error(new RuntimeException("This vanishes"));
})
.onErrorContinue((throwable,o) -> {
System.out.println("8");
}))
.doOnError(__ -> System.out.println("9"))
.onErrorContinue((throwable,obj) -> System.out.println("10"))
.subscribe();
}
当 webClient
尝试与未应答的 uri 对话时,实际会发生此问题,并引发连接被拒绝异常。正如您在代码中看到的那样,有多个 Xerror
操作符(当然只是为了 PoC 放置的)但是这里唯一真正起作用的是带有 onErrorContinue
的 8
。预计 9
和 10
不会工作,因为“错误”已在 8
上解决,但是!如果我注释掉 8
,那么它会跳过 9
并直接转到 10
。最后,无论情况如何,它总是会跳过 1
和 2
运算符。
阅读 reactor 的文档和上面 doOnError
的 javadoc 可以说,它清楚地说明对于 Xerror
运算符,它可以处理任何异常发生在这里。
最后但并非最不重要的一点是删除 onErrorContinue
,1
、2
和 9
按预期工作。因此,如果 onErrorContinue
是一个急切地消耗所有内容的问题,我如何使用“catchAll”故障保护,以防在特定情况下未“预测”错误或只是处理错误?
为了完成本demo-project中使用的pom代码如下
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.5.3</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>demo</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>11</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。