我正在使用响应式(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::doOnSuccess
在 Mono
成功完成(管道已组装)时在执行时触发。
请注意,在像 doOnNext
或 map
这样的中间运算符中,您可以自由地抛出异常,因为 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")?
您可以将 doOnSuccess
和 map
替换为 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/