EntityManager exception handling in session bean

前端 未结 1 691
被撕碎了的回忆
被撕碎了的回忆 2021-02-10 22:18

I have a managed stateless session bean with injected EntityManager em.

What I am trying to do is to have a database table with unique column. Then I run some algorithm

1条回答
  •  生来不讨喜
    2021-02-10 22:49

    I have a suggestion which is I use in my application. We can retrieve the SQLException from PersistenceException. After that, try to get sql error code for SQLException. If your requirement is to get the sql error code, your can follow my example;

    public void insert(Group group) throws DAOException {
        try {
            //your operation
            em.flush();
            logger.debug("insert() method has been successfully finisehd.");
        } catch (PersistenceException pe) {
            String sqlErroCode = getErrorCode(pe);
            // do your operation based on sql errocode
        }
    }
    
    protected String getErrorCode(RuntimeException e) {
        Throwable throwable = e;
        while (throwable != null && !(throwable instanceof SQLException)) {
            throwable = throwable.getCause();
        }
        if (throwable instanceof SQLException) {
            Properties properties = --> load sql error code form configuration file.
            SQLException sqlex = (SQLException) throwable;
            String errorCode = properties.getProperty(sqlex.getErrorCode() + "");
            return errorCode;
        }
        return "NONE";
    }
    

    Example error code configuration of mysql

    mysql_error_code.properties

    #MySQL Database
    1062=DUPLICATE_KEY_FOUND
    1216=CHILD_RECORD_FOUND
    1217=PARENT_RECORD_NOT_FOUND
    1048=NULL_VALUE_FOUND
    1205=RECORD_HAS_BEEN_LOCKED 
    

    0 讨论(0)
提交回复
热议问题