【发布时间】:2022-11-02 15:43:35
【问题描述】:
我的方法看起来像:
public Optional<UserDTO> getUser(String id) {
if (userRepository.findById(Integer.valueOf(id)).isPresent()) {
return userRepository.findById(Integer.parseInt(id))
.map(this::map);
}
throw new UserNotFoundException("User wasn't found");
}
但我想用 try{} catch(){} 块来实现它,我试图让它像这样:
public Optional<UserDTO> getUser(String id) {
try {
userRepository.findById(Integer.valueOf(id)).isPresent();
return userRepository.findById(Integer.parseInt(id))
.map(this::map);
} catch (UserNotFoundException userNotFoundException){
var message = "User wasn't found";
System.out.println(message);
}
}
但它没有在 id 错误的情况下引发异常,并显示没有返回块的错误。
你能帮我找到可能的解决方案吗?
【问题讨论】:
标签: java rest exception try-catch