在 Glassfish 中捕获 MySQL 异常
到目前为止,我已经避免了捕获特定 MySQL 异常的问题,如 MySQLIntegrityConstraintViolationException 等。但现在我需要它来告诉用户他违反了约束,应该选择不同的字符串键。我尝试使用 instanceof
运算符捕获特定异常,因为 Glassfish 将其包装在 EJBException
中。但到目前为止我还没有成功做到这一点。
有没有人有正确的代码/模式来捕获应用程序容器中的特定 SQL 异常(如 Glassfish)?
最好的问候克里斯。
附言。我正在使用 Glassfish 3.1 和 JPA 2.0
I have avoided the problem so far of trapping specific MySQL Exceptions as MySQLIntegrityConstraintViolationException
, 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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
对于大多数数据库访问框架、库或 API,不可能预测所有会导致失败的场景。
在 JPA 中,API 中存在映射到遇到的常见故障的异常。大多数异常都是
PersistenceException
类,或其子类,例如EntityExistsException
,EntityNotFoundException
,NonUniqueResultException
等。您可以捕获这些特定的异常并发出适当的错误消息。您还可以使用 Bean 验证 API,在持久化 JPA 实体之前验证它们的状态,以便您可以减少捕获异常的可能性,这些异常需要不同的错误消息以及最终用户采取的纠正措施。
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 likeEntityExistsException
,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.