Exception trapping for logging, using AOP with CDI in Java EE 7

1

Below I have part of a class, of which I want to eliminate the repetitive logging code through AOP.

/**
 * Javadoc omitido
 */
public abstract class JpaDao<T extends LongIdentifiable> implements
        GenericDao<T> { 

    @Override
    @Transactional
    public Long persist(T type) throws GeneralPersistenceException {
        if (type == null) {
            throw new GeneralPersistenceException("Can't persist null");
        }

        try {
            entityManager.persist(type);
            return type.getId();
        } catch (PersistenceException e) {
            String message = "Failed to persist an entity";
            logger.error(message, e);
            throw new GeneralPersistenceException(message, e);
        }

    }

    @Override
    @Transactional
    public T merge(T type) throws GeneralPersistenceException {
        if (type == null) {
            throw new GeneralPersistenceException("Can't merge null");
        }

        try {
            T mergedType = entityManager.merge(type);
            return mergedType;
        } catch (PersistenceException e) {
            String message = "Failed to merge an entity";
            logger.error(message, e);
            throw new GeneralPersistenceException(message, e);
        }
    }
}

Note that the following code snippet is very repetitive in the persist and merge methods, plus I believe log writing can be handled elsewhere:

} catch (PersistenceException e) {
    String message = "Failed to persist an entity";
    logger.error(message, e);
    throw new GeneralPersistenceException(message, e);
}

The candidate code to replace the above excerpt is as below:

} catch (PersistenceException e) {
    throw new GeneralPersistenceException("Failed to persist an entity", e);
}

In other words, I'd like every time a GeneralPersistenceException was posted, a log message was written. Below is my Exception:

public class GeneralPersistenceException extends Exception {
    private static final long serialVersionUID = -6057737927996676949L;

    public GeneralPersistenceException() {
    }

    public GeneralPersistenceException(String message) {
        super(message);
    }

    public GeneralPersistenceException(String message, Throwable cause) {
        super(message, cause);
    }

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

As you can see, it only has builders. Given this premise, I have the following doubts:

  • The best strategy to solve the problem in a Java EE 7 application is AOP with CDI?
  • If it's AOP, should I intercept the GeneralPersistenceException ?
  • Is it possible to intercept constructors of GeneralPersistenceException , or only methods (which do not yet exist)?
  • Is there something ready for this and I'm reinventing the wheel?
  • asked by anonymous 14.05.2015 / 21:38

    0 answers