Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Catch Hibernate exceptions in Quarkus

I'm trying to build a small REST service using Quarkus. I'm using Hibernate and a PostgreSQL database. It works pretty well in all good cases. But when there are Hibernate exceptions like ConstraintViolationException I'm not able to catch them in a normal way. The exceptions are wrapped with to other exception ArcUndeclaredThrowableException and RollbackException. So the exceptions can just be catched by using

catch (ArcUndeclaredThrowableException e) {
...
}

Repository

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

Resource

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

Because of this issue it's also not possible to add an ExceptionMapper for HibernateExceptions. Does anybody had similar problems or is there a general problem with my code? I'm using Java11.

like image 305
Auskennfuchs Avatar asked Jan 24 '26 23:01

Auskennfuchs


2 Answers

You can flush the Hibernate session this should triggers exceptions like ConstraintViolationException without commiting the transaction.

In your case this should be something like

@Dependent
public class UserRepository {

    @Transactional
    public void createUser(User user) {
        getEntityManager().persist(user);
        getEntityManager().flush();// should triger ConstraintViolationException
    }
}
like image 64
loicmathieu Avatar answered Jan 27 '26 14:01

loicmathieu


I would do it this way :

    try {
        getEntityManager().persist(user);
        getEntityManager().flush();
} catch(ConstraintViolationException e) {
    throw new MyCustomException(e);
}

And create Exception mapper for MyCustomException.

like image 20
iabughosh Avatar answered Jan 27 '26 14:01

iabughosh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!