有没有办法合并多个单声道错误信号?

use*_*066 2 java mono flux project-reactor spring-webflux

有没有办法合并多个错误信号?例如:

    return Mono.zipDelayError(
        monoOne(), //throws ValidationException with list of validation details 1
        monoTwo(),
        monoThree() //throws ValidationException with list of validation details 2
    )
    .then();
}
Run Code Online (Sandbox Code Playgroud)

因此,我想返回 ValidationException 以及合并的验证详细信息列表

Mic*_*rry 5

您可以使用Exceptions.unwrapMultiple()实用程序方法来获取List<Throwable>,然后允许您将该列表减少为单个ValidationException(或进行您喜欢的任何其他检查/处理。)

那么只需将上面的内容包装在onErrorMap()

Mono.zipDelayError(
        Mono.error(new ValidationException("Reason 1")),
        Mono.just("ok"),
        Mono.error(new ValidationException("Reason 2"))
)
.onErrorMap(e ->
        Exceptions.unwrapMultiple(e).stream()
                .reduce((e1, e2) -> new ValidationException(String.join(", ", e1.getMessage(), e2.getMessage()))).get()
);
Run Code Online (Sandbox Code Playgroud)

...这使:

Exception in thread "main" reactor.core.Exceptions$ReactiveException: ValidationException: Reason 1, Reason 2
Run Code Online (Sandbox Code Playgroud)

请注意,这Exceptions.unwrapMultiple()仍然适用于异常不是多个的情况 - 在这种情况下,您只会得到一个单例列表。