bluefoot
bluefoot

Reputation: 10580

How to check, throw and catch bean's validation ConstraintViolationException

Consider the following case:

If some constraint is violated, ClientService receives a ConstraintViolationException. But ClientService only expects DaoException or any other Exception of the "dao" module. And I want to keep it that way, throwing exceptions only related directly to the task that the object does, hiding implementation details for the higher layer (in that case, the "service" module).

What I would like to do is encapsulate javax.validation.ConstraintViolationException in a ValidationException of my "dao" module, and declare it in the trows clause, alongside with DaoException. AND I don't want to perform the validation checks by myself (that's why I use the @Valid annotation)

here is the code (abstracting interfaces, injections and everything else. to make it simple)

package service;

class ClientService {
    insert(Client c) throws ServiceException {
        try {
            new ClientDao().insert(c);
        } catch( DaoException e) {
            throw new ServiceException(e);
        }
    }
}

package dao;

class ClientDao {
    insert(@Valid Client c) throws DaoException {
        myEntityManagerOrAnyPersistenceStrategy.insert(c);
    }
}

I would like to change the dao class to something like:

package dao;

class ClientDao {
    insert(@Valid Client c) throws DaoException, MyValidationException {
        myEntityManagerOrAnyPersistenceStrategy.insert(c);
    }
}

But I have no idea how to do this in the way I described.

FTR, I'm using Spring Web Flow and Hibernate in this project. The dao module contains @Repository classes and the service module contains @Service classes.

Upvotes: 4

Views: 9966

Answers (1)

axtavt
axtavt

Reputation: 242686

Perhaps I don't understand something, but I guess in your case validation is performed automatically by persistence provider and has nothing to do with your @Valid annotation.

If so, you can simply catch ConstraintViolationException inside your DAO method:

class ClientDao {
    insert(@Valid Client c) throws DaoException, MyValidationException {
        try {
            myEntityManagerOrAnyPersistenceStrategy.insert(c);
        } catch (ConstraintViolationException ex) {
            throw new MyValidationException(...);
        }
    }
}

Upvotes: 2

Related Questions