首页 > 解决方案 > Mono.error 中的日志被输出两次

问题描述

出于某种奇怪的原因,“未找到用户”日志在我的应用程序的日志中输出了两次,尽管只调用了一次 findUserById。我不确定是什么导致了这个问题。

有没有更好的方法来解决这个问题(记录并抛出异常)?

请注意,findById调用是 API。

编辑:似乎只抛出一次异常。此外,如果我替换Mono.errorMono.defer,日志也会打印两次。

public Mono<User> getUser(String id) {
    
    Mono<User> thisIsEmpty = getNoUser(); // Assume that this is empty

    return Mono.defer(() -> thisIsEmpty.switchIfEmpty(Mono.defer(() -> findUserById(id))));
}


public Mono<User> findUserById(String id) {
        log.info("This is printed once.");
        Mono<User> user = repository.findById(id).switchIfEmpty(Mono.error(() -> { // findById is an API call of a library I use
            log.error("User not found (this is printed twice)"); // Gets printed twice
            throw new UserException(MY_ERROR_CODE, 401);
        }));

        user.subscribe(User -> ... // Do something if it is not empty

        return user;
}

标签: javareactive-programmingspring-webfluxproject-reactor

解决方案


好吧,来自Mono#error docs

创建一个在订阅后立即以错误终止的 Mono。Throwable 由供应商生成,每次有订阅时调用,并允许延迟实例化。

首先,您的订阅在这里:

user.subscribe(User -> ...

我假设您在代码中有另一个订阅,它使用 getUser。

这就是它被打印两次的原因。


推荐阅读