As already noted, there are two possible approaches: one must test, then insert / update, otherwise handle SQL Exception. Both of these approaches have their drawbacks:
- The caveat "Test before insertion" is that each transaction will have additional queries that will affect performance. This is a particularly big problem when there are few such erroneous transactions.
- The caveat for "evaluating SQL exceptions" is that such exception messages are database specific. These messages, in most cases, do not provide specific information, except that there is a restriction on the violation.
So, I will propose an approach that is a hybrid of the two .
- Do not perform the test before inserting.
- Let the database throw an exception.
- Throw SQL Exception.
- In the stream of exceptions (catch block), make additional requests to generate very specific error messages to indicate to clients what exactly failed (unique key, primary key, foreign key, specific columns, etc.).
This may require a few extra lines of code, but it definitely improves performance and generates friendly error messages.
source share