Throwing catch exception in JSF + EJB application

I am using Glassfish 3.1 with JSF2 and EJB independent to query and write Oracle DB. The table the user wants to populate in this web application has a primary key. When the user tries to add a new entry, the ejb method is called, calling em.persist. Now if the user tries to add a record with the primary key value already in use, I got an exception in the EJB. I would like to display a message to the user indicating an error in the database, but I cannot figure out how the JSF managed bean could catch the EJB exception. Is there a way?

+3


source to share


2 answers


EJB has the concept of system exceptions and application exceptions.

Runtime exceptions such as EntityExistsException

are system exceptions. They cause, among other things, to rollback the transaction and throw an exception (destroy) the EJB bean instance. Most importantly for your problem, they will be wrapped in EJBException

.

There is no magic in these exceptions. Setting up the code from Peter above,
only the following will work:

Bean support:

@EJB
private DAOBean daoBean;

public void savePerson(Entity e) {
     try {
         daoBean.save(e);
     } catch (EJBException e) {         
         FacesMessage message = new FacesMessage("entity is already exists.");
         FacesContext.getCurrentInstance.addMessage(null, message);
     }         
}

      

EJB:

private EntityManager em;

public void save(Entity e) {    
    em.persist(e);    
}

      



Note that you can get the reason for the exception to see if it was EntityExistsException

or not (omitted above for brevity).

Since you probably do not need to destroy your copy of the EJB in this case, the best pattern is to define your own exception, which is derived from RuntimeException

and is annotated using @ApplicationException

the attribute rollback

set to true.

eg.

@ApplicationException(rollback = true)
public class MyException extends RuntimeException {

    public MyException(Throwable cause) {
        super(cause);
    }
}

      

Wrap your EntityExistsException

in your EJB in this exception and throw it and catch it.

I highly recommend you DO NOT use error codes or boolean success / failure as a result. This is a well-known anti-pattern and makes your code an incredible error.

+7


source


You can create your own exception class. Let's say UserException

with an enumeration of the values โ€‹โ€‹of a possible exception.

In EJB, you can define your methods as throws. If you need to throw an exception.



In your JSF-SiteBean, you only need to use a simple try / catch.

Is an exception from type UserException ... get enum reason ... etc.

+2


source







All Articles