how do you handle and parse JPA persistence exceptions to provide meaningfull message to user

后端 未结 5 1664
慢半拍i
慢半拍i 2020-12-30 23:13

I am fairly new to JPA and want to find best practices when handling persistence exceptions from JPA for things like say, unique constraint violations which can be

5条回答
  •  北海茫月
    2020-12-31 00:01

    There are subclasses of PersistenceException: EntityExistsException, EntityNotFoundException, NonUniqueResultException, NoResultException, OptimisticLockException, RollbackException, TransactionRequiredException. Source: http://docs.oracle.com/javaee/5/api/javax/persistence/PersistenceException.html

    You can use them. Try to check the type of exception or overload an error handling method (which is better). EntityExistsException I think the error you are searching for in the example you gave above. But you should check "if it exists" yourself. That's the best practice.

    The SQL Error should never be needed to shown to the user. That error is always for you. Any data related error which needs informing user must be checked manually.

    I use J2EE Web Environment. I just forward the request to error.jsp if there's an exception. I also provide an extra object for error.jsp to clarify the information like user can go back, can go which page after error etc. Of course I automated this, I don't like writing redundant code, because it is hard to update. So I just write send the exception and error message to another class in the catch block.

提交回复
热议问题