【发布时间】:2021-07-28 14:55:39
【问题描述】:
我正在使用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 运算符,它包含any 此处不会发生的异常。
最后但并非最不重要的一点是删除 onErrorContinue 1、2 和 9 按预期工作。因此,如果 onErrorContinue 是一个急切地消耗所有东西的问题,我该如何使用“catchAll”故障保护,以防在特定情况下无法“预测”错误或者只是处理错误?
只是为了完成这个演示项目中使用的 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>
【问题讨论】:
标签: java spring webclient reactor