Best practices for handling unique constraint violation at UI level
While working in my application i came across a situation in which there are likely chances to Unque Constraints Violation.I have following options
- Catch the exception and throw it back to UI
- At UI check for the exception and show approrpriate Error Message
- This is something different idea is to Check in advance about the existance of the given Unique value before starting the whole op开发者_JAVA百科eration.
My Question is what might be the best practice to handle such situation.Currently we are using combo of Struts2+Spring 3.x+Hibernate 3.x
Thanks in advance
edit
In case we decide to let database give tha final verdict and we will handle the exception and propagte that exception to UI and will show Message as per the Exception.What you suggest should be propagate the same exception (org.hibernate.exception.ConstraintViolationException
) to UI layer or should we create a seperate exception class for this since propagating Hibernate exception to UI means polluting the UI classes with Hibernate specific imports and other things
The best way to answer this question is to split it into two ideas.
1) Where is the unique constraint ultimately enforced? In this case (from your question) the answer is the database.
2) How can we make the user experience better by checking the constraint in other places?
Because the database will ultimately make the decision within a transaction, there is no useful check you can make ahead of time. Even if you check before inserting, it is possible (though usually highly unlikely) that another user inserts that value in time between the check and the actual insert.
So let the database decide and bubble the error back up to the UI.
Note that this is not always true for all constraints. When checking foreign keys for small tables (such as a table of US States or Countries or Provinces), the UI provides the user with a selection list, which forces the user to pick an allowed value. In this case the UI really is enforcing the constraint. Though of course even in that case the database must make the final enforcement, to protect against malicious hand-crafted requests to the web layer that are trying deliberately to put in invalid values.
So, for some constraints, yes, let the UI help. But for unique constraints, the UI really cannot help because the database is the final authority, and there is no useful check you can make that you can guarantee will still be true when you make the insert.
Depends on the UI and if the user can do anything about it, as well as what else is going on in the system. I usually check before attempting an insert, especially if there's any sort of transactional logic, or other inserts happening after this one. If there's nothing like that, and the user can just pick a different number to put in, then catching the exception and displaying an error message might be just fine.
精彩评论