I've looked around for help with this issue but actually I don't have any idea where the problem is coming from so I don't know what to look for.
To be simple: - I have a form that persist an object in DB in Ajax generated by JSF using JPA. - When there is a PersistenceException I want to handle it and send a message to the user.
In my DAO I catch PersistenceException and throw a new custom DAOException to my Backing Bean in order to add a FacesMessage to the view.
Facelet :
<h:outputLabel for="codePF" styleClass="control-label">Code PF <span class="requis">*</span>
</h:outputLabel>
<h:inputText id="codePF" value="#{gestionDemandes.demande.motCle}" required="true" size="20" maxlength="20" styleClass="form-control">
<f:ajax event="blur" render="codePFMessage" />
</h:inputText>
<h:message id="codePFMessage" for="codePF" errorClass="erreur" />
<br />
<h:messages globalOnly="true" infoClass="info" />
<h:commandButton id="boutonDemande" value="Inscription" action="#{gestionDemandes.creerDemande()}" styleClass="btn btn-primary">
<f:ajax execute="@form" render="@form" />
<h:message id="boutonDemandeMessage" for="boutonDemande" errorClass="bg-danger" infoClass="bg-success" />
</h:commandButton>
<br />
</h:form>
Backing Bean:
@ManagedBean
@RequestScoped
public class GestionDemandes implements Serializable {
private static final String ERREUR_AJOUT = "Erreur de création de la demande";
private static final String SUCCES = "Demande ajoutée !";
// Injection de notre EJB (Session Bean Stateless)
@EJB
private DAODemande daoDemande;
// Demande utilisée par le formulaire de création de demandes
public void creerDemande() {
FacesMessage message;
try {
daoDemande.creer(demande);
} catch (DAOException dao) {
message = new FacesMessage(FacesMessage.SEVERITY_ERROR, ERREUR_AJOUT,
dao.getMessage());
FacesContext.getCurrentInstance().addMessage(null, message);
return;
}
message = new FacesMessage(SUCCES);
FacesContext.getCurrentInstance().addMessage(null, message);
}
DAO:
@Stateless
public class DAODemande {
// Injection du manager
@PersistenceContext(unitName = "gamabddactuelle_PU")
private EntityManager em;
// Enregistrement d'un nouvel utilisateur
public void creer(Demande demande) throws DAOException {
demande.setIdDemande(demande.getIdClientDemande());
try {
em.persist(demande);
em.flush();
} catch (PersistenceException e) {
throw new DAOException(e.getCause());
}
}
First, I had to add the em.flush() in DAO or I wouldn't even catch the PersistenceException.
Then when I throw my DAOException, I don't catch it in my Backing Bean. It seems the DAOException is thrown in an other thread than the Ajax Call where I persist my Object.
I read this : Better Exception Handling in JPA
Honestly I found it a bit complicated just to handle a simple Exception.
Can someone explain what is going on here ? Is it a thread problem ?
My Conf: TOMEE 7 with/Openjpa 2.4/myfaces 2.2.8 JRE 1.8