弄清楚“哪个约束”?违反了 SQLException
对于许多不同的约束,我的代码可能会遇到“约束违反异常”(CVE)。为了向用户显示有意义的消息并采取特定操作,我正在解析由 getMessage()
返回的 String
。它可以工作,但很丑陋,而且肯定不容易维护。
我想知道是否有更好的方法?这一定是一个很常见的场景;有我可以遵循的模式或最佳实践吗?
谢谢。
My code can encounter a 'Constraint Violation Exception' (CVE) for a number of different constraints. In order to display a meaningful message to the user and to take specific action I am parsing the String
returned by getMessage()
. It works but is ugly and surely not easy to maintain.
I'm wondering if there is a better way? This must be a pretty common scenario; is there a pattern or best practice I could follow?
Thank you.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
AFAIK,因为您对特定约束失败感兴趣,所以无论您做什么都是唯一的出路。
我不确定您在谈论哪个数据库,但您可以尝试..
SQLException.getErrorCode()
和SQLException.getSQLState()
。这些将为您提供更多信息,具体取决于数据库供应商。例如,在 Oracle 中,
SQLException.getErrorCode()
只会告诉您违反了约束,而不一定是哪个约束。AFAIK, since you are interesting in which specific constraint failed, whatever you are doing is the only way to go.
I am not sure which database you are talking about, but you might try..
SQLException.getErrorCode()
andSQLException.getSQLState()
. These would give you more information depending on the db vendor.For example, in Oracle,
SQLException.getErrorCode()
would just tell you a constraint is violated, not necessarily which constraint.