gpt4 book ai didi

java - 如何处理 ifPresent 内部的异常?

转载 作者:行者123 更新时间:2023-11-30 07:45:42 26 4
gpt4 key购买 nike

在方法内部,需要一个条件来执行逻辑。我的 IDE 中出现未处理的异常警告消息。用 try-catch 包裹整个 block 不会让消息消失。

public void changePassword(String login, String currentClearTextPassword, String newPassword) {

userRepository.findOneByLogin(login)
.ifPresent(user -> {
String currentEncryptedPassword = user.getUserSecret();
String encryptedInputPassword = "";
try {
encryptedInputPassword = authUtils.encrypt(currentClearTextPassword);
} catch (Exception ex) {
System.err.println("Encryption exception: " + ex.getMessage());
}
if (!Objects.equals(encryptedInputPassword, currentEncryptedPassword)) {
throw new Exception("Invalid Password"); // <-- unhandled exception
}
String encryptedNewPassword = "";
try {
encryptedNewPassword = authUtils.encrypt(newPassword);
} catch (Exception ex) {
System.err.println("Encryption exception: " + ex.getMessage());
}
user.setUserSecret(encryptedNewPassword);
userRepository.save(user);
log.debug("Changed password for User: {}", user);
});
}

如何处理这个警告信息?

最佳答案

在流操作中处理异常有点开销,我想分离操作并使其像这样:

public void changePassword(String login, String currentClearTextPassword, String newPassword) throws Exception {
//get the user in Optional
Optional<User> check = userRepository.findOneByLogin(login);

//if the user is present 'isPresent()'
if(check.isPresent()){

//get the user from the Optional and do your actions
User user = check.get();

String currentEncryptedPassword = user.getUserSecret();
String encryptedInputPassword = "";
try {
encryptedInputPassword = authUtils.encrypt(currentClearTextPassword);
} catch (Exception ex) {
throw new Exception("Encryption exception: " + ex.getMessage());
}
if (!Objects.equals(encryptedInputPassword, currentEncryptedPassword)) {
throw new Exception("Invalid Password"); // <-- unhandled exception
}
String encryptedNewPassword = "";
try {
encryptedNewPassword = authUtils.encrypt(newPassword);
} catch (Exception ex) {
throw new Exception("Encryption exception: " + ex.getMessage());
}
user.setUserSecret(encryptedNewPassword);
userRepository.save(user);
log.debug("Changed password for User: {}", user);
}
}

除了打印之外,还应该抛出异常。

关于java - 如何处理 ifPresent 内部的异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51503870/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com