开发者

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

开发者 https://www.devze.com 2023-03-27 18:49 出处:网络
I have a question related to String.format in JAVA. My HibernateDao Class is responsible for persisting entities and will throw an e开发者_运维问答xception in case I have any constrain violation. The

I have a question related to String.format in JAVA. My HibernateDao Class is responsible for persisting entities and will throw an e开发者_运维问答xception 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.


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 :)

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号