I wrote a user registration service which should throw an Exception if the user already exists. Here is the code for the register method:
public User register(User user, String role) throws UserExistsException{
boolean userExists = existUserInDB(user);
if(userExists) {
logger.info("Yes, this user exists!");
throw new UserExistsException("This user already exists in database!");
}
try {
String encryptedPassword = getEncryptedPassword(user.getPassword(), getSalt(user));
user.setPassword(encryptedPassword);
Role userRole;
if (role == null){
TypedQuery<Role> query = entityManager.createQuery(
"SELECT r "+
"FROM Role r "+
"WHERE rolename = 'User'", Role.class);
userRole = query.getSingleResult();
} else {
TypedQuery<Role> query = entityManager.createQuery(
"SELECT r "+
"FROM Role r "+
"WHERE rolename = '"+role+"'", Role.class);
userRole = query.getSingleResult();
}
user.getRoles().add(userRole);
userRole.getUsers().add(user);
entityManager.persist(userRole);
entityManager.persist(user);
} catch (NoSuchAlgorithmException | NoSuchProviderException e) {
logger.warning("CryptAPI faild: " + e.getMessage());
}
return user;
}
The logging confirms, that the existUserInDB method returns the correct boolean value. The given user exists in the database. But the exception is never thrown. I have a lot of self implemented Exceptions in my application which all are thrown and catched correctly. All but this one. Can somebody help me with this?
And here is the code where I call the register method.
public String register() {
regUser.setEmail(this.emailAdd);
try {
userService.register(regUser, userRole);
FacesContext context = FacesContext.getCurrentInstance();
context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO,"Der Benutzer wurde erfolgreich registriert.", null));
context.getExternalContext().getFlash().setKeepMessages(true);
} catch (UserExistsException e) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR,"Der Benutzer ist bereits registriert!", null));
}
curSession.setCurrentUser(regUser);
init();
return "home.xhtml?faces-redirect=true";
}
And here is the class definition of the exception:
public class UserExistsException extends Exception {
private static final long serialVersionUID = -9218609941894034576L;
public UserExistsException(){
super();
}
public UserExistsException(String message){
super(message);
}
}
With the help of all above I was able to solve it. The problem was not the thrown exception. Sorry for the incorrect title. The problem was the redirect I had in the return statement of the calling method. So my FacesMessage got lost. I fixed it with the following lines in the catch clause:
FacesContext context = FacesContext.getCurrentInstance();
context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR,"Der Benutzer existiert bereits.", null));
context.getExternalContext().getFlash().setKeepMessages(true);
Thank you to all persons above for guiding me to the right path.