Saturday, 31 August 2013

Using exceptions for control flow

Using exceptions for control flow

I have read that using exceptions for control flow is not good, but how
can I achieve the following easily without throwing exceptions? So if user
enters username that is already in use, I want to show error message next
to the input field. Here is code from my sign up page:
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";
}
save method of my 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);
}

No comments:

Post a Comment