java - Mono.error 中的日志被输出两次
问题描述
出于某种奇怪的原因,“未找到用户”日志在我的应用程序的日志中输出了两次,尽管只调用了一次 findUserById。我不确定是什么导致了这个问题。
有没有更好的方法来解决这个问题(记录并抛出异常)?
请注意,findById
调用是 API。
编辑:似乎只抛出一次异常。此外,如果我替换Mono.error
为Mono.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;
}
解决方案
好吧,来自Mono#error docs:
创建一个在订阅后立即以错误终止的 Mono。Throwable 由供应商生成,每次有订阅时调用,并允许延迟实例化。
首先,您的订阅在这里:
user.subscribe(User -> ...
我假设您在代码中有另一个订阅,它使用 getUser。
这就是它被打印两次的原因。
推荐阅读
- jupyter-notebook - 编写一个实现网桥检测算法的函数
- asp.net-core - 如何配置 .NET Core Identity 以使用 Kubernetes
- javascript - 延迟加载图像和替换
- r - +/- 列名称折叠和求和
- javascript - 从角度调用.net核心方法给出错误:加载资源失败:服务器响应状态为404()
- powershell - 在带有预定义变量的 ps1 脚本中启动 powershell.exe
- cassandra - 限制列文本大小,如 SQL
- r - 按名称连接两个列表中的向量
- python - 具有多个对的 AssetPairs 查询
- android - RecyclerView Multiple ViewHolders ItemDetailsLookup