How can i catch this Exception :
com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException:
Duplicate entry '22-85' for key 'ID_CONTACT'
How can i catch this Exception :
com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException:
Duplicate entry '22-85' for key 'ID_CONTACT'
vendorCode
2601
is forunique index constraint
violate so you can check SQLException cewndorCode bye.getErrorCode() == 2601
. sample code:I agree, but we've something like this in my Spring Application,:- RequestValidationException/MessageConstants are custom one's:
A - Log the exception in detail
Here is what I use to log SQL Exceptions so that I can be sure of what to catch;
Here is the sample Output;
B - Catch the Exception and check the parameters
To catch duplicate key Exception, we need to catch the specific class which is
MySQLIntegrityConstraintViolationException
. Also the following parameter must match;So I use the following block to catch duplicate entries;
The following code works for me:
catch SQLIntegrityConstraintViolationException, if you are using Java 1.6+
e.g.
or
I use spring so we resolve it by
org.springframework.dao.DataIntegrityViolationException
But as @KevinGuancheDarias mention it: