我有以下代码,RepositoryException将由全局ExceptionHandler处理。
public Category update(Category entity) {
try {
em = emf.createEntityManager();
em.getTransaction().begin();
Category category = em.find(Category.class, entity.getId());
if(category == null)
//is this okay?
throw new RepositoryException("category not found");
category.setName(entity.getName());
em.getTransaction().commit();
return entity;
} catch (PersistenceException e) {
em.getTransaction().rollback();
if (e.getCause().getCause() instanceof ConstraintViolationException
&& ((ConstraintViolationException) e.getCause().getCause()).getSQLException().getMessage()
.contains("UC_categories_name"))
throw new RepositoryException("category already exists");
throw e;
} finally {
em.close();
}
}
如果您知道另一种在最小化数据库查询数量的同时更新实体的方法,您可以评论它。
确实,在找不到类别时选择抛出像 RepositoryException 这样的自定义异常是一种合理的方法,因为它使调用代码能够适当地处理这种情况。但是,必须确保 RepositoryException 类定义良好,并为调用代码提供足够的信息以了解根本问题。
例如,您可以创建一个异常层,在其中包含自定义异常,也许还可以创建一个枚举类来定义您使用的所有类型的异常。
示例:创建一个具有异常处理程序、异常响应和错误类型(枚举)的包以获得更好的结构。