可选,有多个例外
Optional with multiple exceptions
我有以下代码片段,我想使用可选值重写
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);
}
我卡在无法根据用户名和电子邮件抛出特定异常的部分。 我可以 return null 如果它们之一已经存在于数据库中并且它会导致 orElseThrow 工作 但具有相同的异常类型。对于两种不同的情况,我想要两个单独的例外。我该如何处理?
我更喜欢更实用的可选用法。
问题是 CheckedException's
并不是为了在 Java 上使用函数式风格而设计的。
Optional
的方法 .map
收到一个 Function,它不会抛出 Exception
。
只需将您的异常转换为 RuntimeException's
即可按预期工作。
...但要小心实例化 throwables(尤其是参数 writableStackTrace,配置为 false 应该没问题),看看:The hidden performance costs of instantiating Throwables
.
如果您对 Java 中的函数式编程方法感兴趣,也可以看看 Vavr,非常好的库并在 Option
上支持 CheckedException's
。
我有以下代码片段,我想使用可选值重写
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);
}
我卡在无法根据用户名和电子邮件抛出特定异常的部分。 我可以 return null 如果它们之一已经存在于数据库中并且它会导致 orElseThrow 工作 但具有相同的异常类型。对于两种不同的情况,我想要两个单独的例外。我该如何处理?
我更喜欢更实用的可选用法。
问题是 CheckedException's
并不是为了在 Java 上使用函数式风格而设计的。
Optional
的方法 .map
收到一个 Function,它不会抛出 Exception
。
只需将您的异常转换为 RuntimeException's
即可按预期工作。
...但要小心实例化 throwables(尤其是参数 writableStackTrace,配置为 false 应该没问题),看看:The hidden performance costs of instantiating Throwables .
如果您对 Java 中的函数式编程方法感兴趣,也可以看看 Vavr,非常好的库并在 Option
上支持 CheckedException's
。