You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Reactor Mono映射时触发NullPointerException问题求助

问题分析与解决方案

错误原因

  1. Reactor map操作符的约束:Reactor框架明确禁止map操作符的映射函数返回null,一旦返回null就会抛出你遇到的NullPointerException,这是为了避免空值在响应式流中传播,引发后续不可预期的问题。
  2. 逻辑适配错误:
    • 如果connectionRepository.findLastTimeConnected()是异步方法(返回Mono<Timestamp>),你使用map会把结果包装成Mono<Mono<Timestamp>>,不符合你要返回Mono<Timestamp>的需求;
    • 如果它是同步方法(返回Timestamp或null),直接用map传递null值会触发框架的空值校验。

针对性解决方案

方案1:当findLastTimeConnected是异步方法(返回Mono<Timestamp>)

使用flatMap代替map,flatMap会自动展开内部的Mono,直接返回你需要的Mono<Timestamp>,同时避免空值异常:

@Override
public Mono<Timestamp> findLastTimeConnected() {
    return SecurityUtils.getUsernameAuthenticated()
            .flatMap(connectionRepository::findLastTimeConnected);
}

如果findLastTimeConnected返回空Mono,流会正常结束,不会抛出异常。

方案2:当findLastTimeConnected是同步方法(返回Timestamp或null)

方式A:过滤null值,返回空Mono

使用mapNotNull操作符,自动过滤映射结果为null的元素:

@Override
public Mono<Timestamp> findLastTimeConnected() {
    return SecurityUtils.getUsernameAuthenticated()
            .mapNotNull(connectionRepository::findLastTimeConnected);
}
方式B:为null值设置默认值

如果需要在结果为null时返回一个默认的Timestamp:

@Override
public Mono<Timestamp> findLastTimeConnected() {
    return SecurityUtils.getUsernameAuthenticated()
            .map(username -> {
                Timestamp result = connectionRepository.findLastTimeConnected(username);
                // 替换为你需要的默认时间戳
                return result != null ? result : new Timestamp(System.currentTimeMillis());
            });
}
方式C:将null转换为空Mono

通过flatMap把null结果转换为空Mono:

@Override
public Mono<Timestamp> findLastTimeConnected() {
    return SecurityUtils.getUsernameAuthenticated()
            .flatMap(username -> {
                Timestamp result = connectionRepository.findLastTimeConnected(username);
                return result != null ? Mono.just(result) : Mono.empty();
            });
}

内容的提问来源于stack exchange,提问作者fernando1979

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 15:55:33