java - Spring webflux 中的异常处理

标签 java spring spring-boot reactive-programming spring-webflux

我正在使用响应式(Reactive)流开发 Spring webflux 项目。我有一个如下的用例,想知道如何以响应式方式完成它。

  @RestController
  public class Example {

    @GetMapping("/greet")
    public Mono<String> Test() {
       return Mono.just("Tim")
               .map(s -> s.toUpperCase())
               .map(s -> s.toLowerCase())
               .doOnSuccess(s -> validate(s)) // usecase is to validate here in middle of the pipeline
               .onErrorResume(ex -> Mono.just("Guest"))
               .map(s -> "Hi, "+s);
    }
   
  public void validate(String s) {
    if(s.length() < 5) {throw new RuntimeException("Name is short");}
  }
 
}

我知道这是一个人为的例子,但我有类似的东西。我认为抛出错误会导致端点被击中时浏览器屏幕上出现异常。但令我惊讶的是,它转到了 onErrorResume() 并且我得到了 Hi, Guest 作为响应。我认为当在响应式(Reactive)管道组装之前使用 throw 抛出异常时,它不会使用 onErrorResume() 。我在这里缺少什么?

同样来到问题#2,如果我使用 Mono.error(new RuntimeException("Name is short")) 而不是 throw new RuntimeException( “名字很短”)?有人可以回答我的两个问题吗?感谢改进代码的建议。

最佳答案

I thought when throw is used to throw an exception before the reactive pipeline is assembled, it will not use onErrorResume()

Mono::doOnSuccessMono 成功完成(管道已组装)时在执行时触发。

请注意,在像 doOnNextmap 这样的中间运算符中,您可以自由地抛出异常,因为 Reactor 可以将它们转换为正确的错误信号,因为此时 Mono 已经在进行中。

how can I achieve this if I'm using Mono.error(new RuntimeException("Name is short")) instead of throw new RuntimeException("Name is short")?

您可以将 doOnSuccessmap 替换为 handle 运算符:

 return Mono.just("Tim")
            .handle((name, sink) -> {
                if(name.length() < 5){
                    sink.error(new RuntimeException("Name is short"));
                } else {
                    sink.next(name.toLowerCase());
                }
            })

关于java - Spring webflux 中的异常处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69231306/

相关文章:

java - 在 Spring Boot 应用程序中集成 Apache guacamole

java - Spring Data JPA 的查询方法如何生成查询?

java - Spring Boot 中的复杂身份验证

java - Solaris 上的 OptaPlanner 比 Linux 操作系统上慢 5 倍

java - Jackson json 双向对象引用

java - 使用 `destroyMethod` 或 `close()` 方法在 bean 返回类型上设置 `shutdown()`

java - Spring数据排序操作超出最大大小

java - Apache POI 确定最后一行的可靠方法

java - 为较低的 sdk/jdk 重建项目。失败 [INSTALL_FAILED_OLDER_SDK]

java - Spring MVC 中的错误 : java. lang.NoSuchMethodException : java. lang.Long.<init>()