String.format using a exception.getMessage() as a format

喜你入骨 提交于 2019-12-23 17:35:15

问题


I have a question related to String.format in JAVA. My HibernateDao Class is responsible for persisting entities and will throw an exception in case I have any constrain violation. The message contains a %s and will be used as a format in the upper layers, as I should be worried about types in this layer, thus can't identify what object I could not persist.

public Entity persistEntity(Entity entity) {
    if (entity == null || StringUtils.isBlank(entity.getId()))
        throw new InternalError(CANNOT_INSERT_NULL_ENTITY);

    try {
        getHibernateTemplate().save(entity);
    } catch (DataAccessException e) {
        if (e.getCause() instanceof ConstraintViolationException)
            throw new HibernateDaoException("%s could not be persisted. Constraint violation.");
        throw new HibernateDaoException(e);
    }

    return entity;
}

And then in my DaoHelper Class I will catch this exception and throw a new one, with a formatted message.

//Correct Code
public Entity create(Entity object) throws MyException {
    try {
        return this.hibernateDao.persistEntity(object);
    } catch (HibernateDaoException he) {
        String format = he.getMessage();
        throw new MyException(String.format(format,object.getClass().getSimpleName()));
    }
}

My question is, why I cannot directly call the he.getMessage() in my String.format method?? And must use a 'tmp' variable instead... It just won't substitute the %s from the string.

//What I wished to do, but I cant.
public Entity create(Entity object) throws MyException {
    try {
        return this.hibernateDao.persistEntity(object);
    } catch (HibernateDaoException he) {
        throw new MyException(String.format(he.getMessage(),object.getClass().getSimpleName()));
    }
}

Thx in advance.


回答1:


This should be closed, as the intended behavior is working. As @Kal and @highlycaffeinated commented, calling the getMessage() directly does work, something must have happened with my build and did not update correctly. However the messages do appear correctly now. Thanks for the quick answers :)



来源:https://stackoverflow.com/questions/7016578/string-format-using-a-exception-getmessage-as-a-format

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!