[英]Catch Hibernate exceptions in Quarkus
我正在嘗試使用 Quarkus 構建一個小型 REST 服務。 我正在使用 Hibernate 和 PostgreSQL 數據庫。 它在所有好的情況下都能很好地工作。 但是當有像ConstraintViolationException
這樣的 Hibernate 異常時,我無法以正常方式捕獲它們。 異常與其他異常ArcUndeclaredThrowableException
和RollbackException
一起包裝。 所以異常可以通過使用來捕獲
catch (ArcUndeclaredThrowableException e) {
...
}
存儲庫
@Dependent
public class UserRepository {
@Transactional
public void createUser(User user) {
getEntityManager().persist(user); //<- the constraint violation happens at commit, so when transaction will be closed
}
}
資源
@Override
public Response createUser(@Valid CreateUserDTO createUserDTO, UriInfo uriInfo) {
...
try {
userRepository.createUser(user);
} catch (ArcUndeclaredThrowableException e) { //<- here the hibernate exception should be catchable
log.error(e.getMessage());
throw e;
}
return Response.ok().build();
}
由於這個問題,也不可能為 HibernateExceptions 添加一個ExceptionMapper
。 有沒有人有類似的問題,或者我的代碼有一般問題嗎? 我正在使用 Java11。
我會這樣做:
try {
getEntityManager().persist(user);
getEntityManager().flush();
} catch(ConstraintViolationException e) {
throw new MyCustomException(e);
}
並為 MyCustomException 創建異常映射器。
您可以刷新 Hibernate 會話,這應該會在不提交事務的情況下觸發ConstraintViolationException
異常。
在你的情況下,這應該是這樣的
@Dependent
public class UserRepository {
@Transactional
public void createUser(User user) {
getEntityManager().persist(user);
getEntityManager().flush();// should triger ConstraintViolationException
}
}
我今天遇到了同樣的問題,並找到了解決方法。 據我所知,問題是 Arc(quarkus 的 cdi 實現)有時需要生成類。
檢查異常(如 javax.transaction.RollbackExcpetion)需要以某種方式傳播給用戶。 因此,已檢查的異常被包裝在 ArcUndeclaredThrowableException 中。 但是,僅當您沒有明確處理異常時才需要這樣做。
例如,您可以聲明異常:
@Dependent
public class UserRepository {
@Transactional
public void createUser(User user) throws RollbackException{
getEntityManager().persist(user);
}
}
在您的資源中,您可以捕獲 RollbackException
@Override
public Response createUser(@Valid CreateUserDTO createUserDTO, UriInfo uriInfo) {
...
try {
userRepository.createUser(user);
} catch (RollbackException e) {
log.error(e.getMessage());
throw e;
}
return Response.ok().build();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.