简体   繁体   English

不抛出Java异常

[英]Java Exception is not thrown

I wrote a user registration service which should throw an Exception if the user already exists. 我编写了一个用户注册服务,如果该用户已经存在,则应该抛出Exception。 Here is the code for the register method: 这是register方法的代码:

    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. 日志记录确认existUserInDB方法返回正确的布尔值。 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. 这是我调用register方法的代码。

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

}

The problem maybe int the line below that will not do the right things which you want. 问题可能在下面的代码行中,该行无法完成您想要的正确操作。

    catch (UserExistsException e) {
          FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR,"Der Benutzer ist bereits registriert!", null));
    }

You can check that code executed here like this: 您可以像这样检查此处执行的代码:

catch (UserExistsException e) {
     System.out.println(">>>>>>>>>>>>>>>>>>");
     FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR,"Der Benutzer ist bereits registriert!", null));
        }

If the line printed, then it means the Exception has been thrown. 如果打印了该行,则表示已引发异常。 But the rest of code did not do the things that you want from. 但是其余的代码并没有完成您想要的事情。

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. 问题是我在调用方法的return语句中具有重定向。 So my FacesMessage got lost. 所以我的FacesMessage迷路了。 I fixed it with the following lines in the catch clause: 我在catch子句中使用以下几行对其进行了修复:

        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. 感谢所有以上指导我走正确道路的人。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM