简体   繁体   中英

JSF 2 : How handle exceptions in controller?

I would like to do a register form which works fine:

<h:form id="register_form">
            <h:panelGrid columns="3">
                <h:outputLabel for="email" value="E-mail:" />
                <h:inputText id="email" value="#{userc.userb.user.email}">
                    <f:ajax event="blur" render="m_email" />
                </h:inputText>
                <h:message id="m_email" for="email" ajaxRendered="false" />

                <h:outputLabel for="password" value="Passoword" />
                <h:inputSecret id="password" value="#{userc.userb.user.password}">
                    <f:validator validatorId="confirmPasswordValidator" />
                    <f:attribute name="confirm" value="#{confirmPassword.submittedValue}" />
                </h:inputSecret>
                <h:message id="m_password" for="password" />

                <h:commandButton value="Registerr" action="#{userc.register}">
                    <f:ajax execute="@form" render="@form" />
                </h:commandButton>
                
                <h:messages globalOnly="true" layout="table" />
                
            </h:panelGrid>
        </h:form>

And this is my controller:

public void register(){
    FacesMessage message;
    try {
        userb.encryptPassword();
        userEAO.create(userb.getUser());
        
        message = new FacesMessage("Register successfully!");
        FacesContext.getCurrentInstance().addMessage(null, message);
    } catch (Exception e) {
        // 1062 : duplicate entry
        if (e.getMessage().contains("Duplicate")){
            message = new FacesMessage("User already registered, please try another email");
            FacesContext.getCurrentInstance().addMessage(null, message);
        }else{
            message = new FacesMessage("An error occured, try again please");
            FacesContext.getCurrentInstance().addMessage(null, message);
        }
    }
    
}

So, for example, if some user try to register himself twice, I return this message, saying that's duplicate, but I wonder if this is the best approach.

How to treat these kinds of exceptions?

Those validations should be handled by your Business Logic Layer object, in this case, it looks like it is the userEAO object. You can decide if you should handle this error messages in the flavor of Exceptions (which IMHO won't use).

In my case, I prefer to use a Message class that basically contains an integer code and a message holding the results of the operation. For my case, I usually return 0 or more to indicate the operation was successful, and use negative codes to declare errors. This is a pretty basic example:

public class Message {
    private int code;
    private String message;
    //constructor...
    //getters and setters...
}

public class UserBL {

    public Message create(User user) {
        //do some fancy validations
        if (!verifyDuplicatedUser(user)) {
            return new Message(-1000, "Duplicated user");
        }
        //and the operations...
        saveUser(user);
        return new Message(0, "Register successfully!");
    }

}

Now your controller will be forward to what it must really do (this means, no heavy business logic validations):

public void register() {
    FacesMessage fmessage;
    userb.encryptPassword();
    Message message = userEAO.create(userb.getUser());
    fmessage = new FacesMessage(message.getMessage());
    FacesContext.getCurrentInstance().addMessage(null, fmessage);
}

This approach can even help you when you should validate a set of data, like validating the results of an Excel sheet and you must show a list of errors (because showing a single error lot of times is very annoying!).

You can improve the way you create the messages, like retrieving them from a table with the messages for your system, or using properties files to handling internationalization (that depends on your functional requirements, of course).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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