I have avoided the problem so far of trapping specific MySQL Exceptions as MySQLIntegrityConstraintViolationExcep开发者_如何学运维tion
, etc. But now I need it to tell the user that he is violating a constraint and should choose a different string key. I've tried to catch the specific exception by using instanceof
operator, since Glassfish is wrapping it in a EJBException
. But I haven't managed to do this so far.
Does anyone have the correct code/pattern to catch the specific SQL exception in an application container as Glassfish ?
Best Regards Chris.
PS. I am using Glassfish 3.1 and JPA 2.0
With most database-access frameworks, libraries or APIs it is impossible to predict all of the scenarios that would result in failures.
In JPA, there are exceptions in the API that map to commonly failures encountered failures. Most of these exceptions are instances of the PersistenceException
class, or it's sub-classes like EntityExistsException
, EntityNotFoundException
, NonUniqueResultException
etc. You could catch these specific exceptions and issue appropriate error messages.
You may also use the Bean Validation API, to verify the state of your JPA entities before persisting them, so that you could reduce the possibilities of catching exceptions that will require different error messages and resulting corrective actions by an end-user.
精彩评论