String.format 使用 exception.getMessage() 作为格式

2024-03-04

我有一个与 JAVA 中的 String.format 有关的问题。 我的 HibernateDao 类负责持久化实体,并在发生任何约束违规时抛出异常。该消息包含 %s 并将用作上层的格式,因为我应该担心这一层中的类型,因此无法识别我无法持久化的对象。

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;
}

然后在我的 DaoHelper 类中,我将捕获此异常并抛出一个新异常,并带有格式化消息。

//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()));
    }
}

我的问题是,为什么我不能在 String.format 方法中直接调用 he.getMessage() ?并且必须使用“tmp”变量...它只是不会替换字符串中的 %s。

//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()));
    }
}

提前谢谢。


这应该关闭,因为预期的行为正在发挥作用。正如 @Kal 和 @highlycaffelated 评论的那样,getMessage()直接工作,我的构建一定发生了一些事情并且没有正确更新。不过,这些消息现在确实显示正确。 感谢您的快速解答:)

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

String.format 使用 exception.getMessage() 作为格式 的相关文章

随机推荐