我读到,使用异常进行控制流不好,但是如何在不引发异常的情况下轻松实现以下目标?因此,如果用户输入已在使用的用户名,我想在输入字段旁边显示错误消息。以下是我的注册页面支持 bean 中的代码:
public String signUp() {
User user = new User(username, password, email);
try {
if ( userService.save(user) != null ) {
// ok
}
else {
// not ok
}
}
catch ( UsernameInUseException e ) {
// notify user that username is already in use
}
catch ( EmailInUseException e ) {
// notify user that email is already in use
}
catch ( DataAccessException e ) {
// notify user about db error
}
return "index";
}
我的 userService 的保存方法:
@Override
@Transactional
public User save(User user) {
if ( userRepository.findByUsername(user.getUsername()) != null ) {
LOGGER.debug("Username '{}' is already in use", user.getUsername());
throw new UsernameInUseException();
}
else if ( userRepository.findByEmail(user.getEmail()) != null ) {
LOGGER.debug("Email '{}' is already in use", user.getEmail());
throw new EmailInUseException();
}
user.setPassword(BCrypt.hashpw(user.getPassword(), BCrypt.gensalt()));
user.setRegisteredOn(DateTime.now(DateTimeZone.UTC));
return userRepository.save(user);
}
最佳答案
使用异常就像您所做的任何其他事情一样。您可以使用它,但不要过度使用。
一般来说,当发生不正确的事情时,您希望抛出异常,但您的程序可以从中恢复,可能是在另一个模块中。异常有助于使程序(更准确地说是运行时堆栈)处于良好状态,以便您可以对错误采取措施。
使用返回值通常不是一个好主意,并且通常被视为不太好的设计。
在您的情况下,异常很可能会向用户触发一条消息,该消息发生在 UI 中,并且应该与注册逻辑本身分开,因此使用异常似乎是合适的。
现在是过度的部分。您可以轻松地执行单个异常,例如 SignupException,其中包含出错的原因。您可能不希望最终得到一个异常类比具有高效代码的类还要多的系统。
关于java - 使用异常进行控制流,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18552293/