【问题标题】:Mono - All the doOnError handlers are getting calledMono - 所有的 doOnError 处理程序都被调用
【发布时间】:2020-10-04 16:46:54
【问题描述】:

我有这个 Mono 代码:

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被调用?

【问题讨论】:

    标签: spring-boot spring-webflux project-reactor


    【解决方案1】:

    当 validate 方法抛出 ValidationException 时,handleValidationException 和 handleException 都会被调用。我希望只调用handleValidationException。为什么会这样?

    ...因为ValidationException 也是Exception 通过继承的实例,并且doOnError() 不会“吞下”异常(因此它仍会传播到下一个doOnError() 调用。

    有几种不同的方法可以处理它 - 我的首选方法通常是使用 onErrorResume() 处理异常并在处理后返回一个空的发布者:

    //...
    .then(execute(operation))
    .onErrorResume(ValidationException.class, e -> {
        this.handleValidationException();
        return Mono.empty();
    })
    .doOnError(Exception.class, ...)
    

    ...如果这是您所追求的行为,那么这将确保错误永远不会“失败”。

    我还想到了另外两种方法,但是,我不太喜欢这些方法。您可以使用谓词在第二个doOnError() 中显式检查它是否不是ValidationException

    .doOnError(e -> !(e instanceof ValidationException), ...)
    

    ...或者您也可以在一个块中处理所有异常,然后检查其中的类型:

    .doOnError(e -> {
        if(e instanceof ValidationException) {
    
        }
        else {
    
        }
    })
    

    【讨论】:

    • 感谢您的回答。我想避免遵循最后一种方法,但这似乎是最简单的。我需要例外,所以我别无选择:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-10-20
    • 2020-09-09
    • 1970-01-01
    • 2011-01-31
    • 2017-01-09
    • 2014-05-01
    • 2016-08-03
    相关资源
    最近更新 更多