Spring boot Mono-所有的doOnError处理程序都被调用
我有一个单声道代码:Spring boot Mono-所有的doOnError处理程序都被调用,spring-boot,spring-webflux,project-reactor,Spring Boot,Spring Webflux,Project Reactor,我有一个单声道代码: return Mono.just(operation) .map(this::validate) .then(execute(operation)) .doOnError(ValidationException.class, this::handleValidationException) .doOnError(Exception.class, this::handleException); 当validat
return Mono.just(operation)
.map(this::validate)
.then(execute(operation))
.doOnError(ValidationException.class, this::handleValidationException)
.doOnError(Exception.class, this::handleException);
当validate方法抛出ValidationException时,将同时调用handleValidationException和handleException。我只想接到handleValidationException的电话。
为什么会这样?如何防止handleException被调用
当validate方法抛出ValidationException时,将同时调用handleValidationException和handleException。我只想接到handleValidationException的电话。为什么会这样
…因为ValidationException
也是通过继承的Exception
的一个实例,并且do出错()
不会“吞没”异常(因此它仍然会传播到下一个do出错()
调用
有几种不同的方法可以处理它-我的首选方法通常是使用onErrorResume()
吞下异常并在处理后返回空发布服务器:
//...
.then(execute(operation))
.onErrorResume(ValidationException.class, e -> {
this.handleValidationException();
return Mono.empty();
})
.doOnError(Exception.class, ...)
…这将确保错误永远不会“漏掉”,如果这是您所追求的行为
然而,我也想到了另外两种方法,我不太喜欢这些方法。您可以使用谓词显式检查第二个doOnError()
中的ValidationException
:
…或者您也可以在一个块中处理所有异常,只需检查其中的类型:
.doOnError(e -> {
if(e instanceof ValidationException) {
}
else {
}
})
谢谢你的回答。我本想避免采用最后一种方法,但这似乎是最简单的方法。我需要通过例外,因此我别无选择:)
.doOnError(e -> {
if(e instanceof ValidationException) {
}
else {
}
})