1

我已经读过使用异常进行控制流不好,但是如何在不引发异常的情况下轻松实现以下目标?因此,如果用户输入已在使用的用户名,我想在输入字段旁边显示错误消息。这是来自我的注册页面支持 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";
}

我的用户服务的保存方法:

@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);
}
4

1 回答 1

0

使用异常的工作方式与您所做的任何其他事情一样。你可以使用它,但不要过度使用它。

通常,当发生不正确的事情时,您希望抛出异常,但您的程序可以从另一个模块中恢复。异常有助于使程序(更准确地说是运行时堆栈)处于良好状态,因此您可以对错误采取一些措施。

使用返回值通常不是一个好主意,并且通常被视为不太好的设计。

在您的情况下,异常很可能会向用户触发一条消息,这发生在 UI 中并且应该与注册逻辑本身分开,因此使用异常似乎是合适的。

现在是过度使用它的部分。您可以轻松地执行单个异常,例如 SignupException,其中包含出错的原因。您可能不想最终得到一个异常类比具有生产性代码的类更多的系统。

于 2013-08-31T20:19:55.547 回答