【问题标题】:Optional with multiple exceptions可选,有多个例外
【发布时间】:2021-11-02 00:57:04
【问题描述】:

我有以下代码 sn-p,我想使用可选项重写

public User signup(UserDTO userDTO) throws Exception {
    User user = modelMapper.map(userDTO, User.class);
    
    if (userRepo.findByEmail(user.getEmail()).isPresent()) {
        throw new EmailAlreadyUsedException();
    }
    
    if (userRepo.findByUsername(user.getUsername()).isPresent()) {
        throw new UsernameAlreadyUsedException();
    }
    
    user.setId(UUID.randomUUID().toString());
    // set other stuff like encoded password
    userRepo.save(user);
}

有了可选项,我可以想出以下方法。

public User signup(UserDTO userDTO) throws Exception {
    return Optional.of(userDTO)
            .map(u -> modelMapper.map(u, User.class))
            .map(user -> {
                user.setId(UUID.randomUUID().toString());
                // set other stuff like encoded password

                // check email and username if they exist

                // save
                userRepo.save(user);
                return user;
            }).orElseThrow(Exception::new);
}

我被困在我无法根据用户名和电子邮件抛出特定异常的部分。 如果其中一个已经存在于 db 中,我可以返回 null,这将导致 orElseThrow 工作,但具有相同的异常类型。对于两种不同的情况,我想要两个单独的例外。我该如何处理?

【问题讨论】:

  • 没有选项的方法可读性更好。想想看。 jm2c
  • 顺便说一句:您的用户 ID 不是唯一的,是吗?创建随机 UUID 会产生冲突。
  • 不要这样做。您的第一个代码 sn-p 易于阅读和理解。 Optional 不会给你带来任何好处。顺便说一句:您的代码不安全(您可以同时插入 2 个具有相同名称和电子邮件的用户)。您应该简单地执行INSERT 并让数据库检查唯一性。或者将您的查询放在一个事务中。
  • 正如其他人所说,您现有的代码看起来更干净。除非你想把“Java 8”写在你的简历上,或者通过 LOC 获得报酬,否则我建议你什么都不做。

标签: java spring optional


【解决方案1】:

我更喜欢功能性更强的可选用法。

问题是CheckedException's 并非设计用于在 Java 上使用函数式样式。 Optional 的方法 .map 接收到 Function,它不会抛出 Exception。 只需将您的异常转换为 RuntimeException's 即可按预期工作。

...但是要小心实例化的 throwable(尤其是参数 writableStackTrace,配置为 false 应该没问题),看看:The hidden performance costs of instantiating Throwables

如果你对 Java 中的函数式编程方法感兴趣,也可以看看 Vavr,非常好的库并支持 Option 上的 CheckedException's

【讨论】:

  • 感谢您的回答。正如你所说,我应该更喜欢运行时异常。
猜你喜欢
  • 2011-10-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-08
  • 2017-09-10
  • 2014-10-30
  • 1970-01-01
相关资源
最近更新 更多