reset password
Author Message
harry_520
Posts: 76
Posted 11:24 Mar 08, 2014 |

How do I avoide the 500 error message "com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Duplicate entry 'ssss' for key 'PRIMARY'" when a username has already been taken? Instead, how do I display the corresponding error message in the console?

Last edited by harry_520 at 12:12 Mar 08, 2014.
redge
Posts: 31
Posted 11:27 Mar 08, 2014 |

Surround the JDBC insert code with a "try" block, catch the exception (either a MySQLIntegrityConstraintViolationException or just a generic Exception), and do whatever you want with it from there.

cysun
Posts: 2935
Posted 11:43 Mar 08, 2014 |
redge wrote:

Surround the JDBC insert code with a "try" block, catch the exception (either a MySQLIntegrityConstraintViolationException or just a generic Exception), and do whatever you want with it from there.

It'd be better to use a SELECT query to check if the username already exists before doing INSERT.

I'm against using exception for these types of checks in general because

a) Conceptually exceptions are for unexpected things; duplicate usernames are common enough that they should be checked as part of the regular procedure.

b) It's often hard to tell the cause of the problem if you just have an exception. For example, an IntegrityConstraintViolation exception may be caused by a foreign key error, and a general exception can be caused by anything, so you won't be able to produce an informative error message like "This username is already taken".

redge
Posts: 31
Posted 11:49 Mar 08, 2014 |
cysun wrote:
redge wrote:

Surround the JDBC insert code with a "try" block, catch the exception (either a MySQLIntegrityConstraintViolationException or just a generic Exception), and do whatever you want with it from there.

It'd be better to use a SELECT query to check if the username already exists before doing INSERT.

I'm against using exception for these types of checks in general because

a) Conceptually exceptions are for unexpected things; duplicate usernames are common enough that they should be checked as part of the regular procedure.

b) It's often hard to tell the cause of the problem if you just have an exception. For example, an IntegrityConstraintViolation exception may be caused by a foreign key error, and a general exception can be caused by anything, so you won't be able to produce an informative error message like "This username is already taken".

From a design perspective, I completely agree. Your second point is especially relevant for this project. That being said, all the original question asked for was a way to "display the corresponding error message in the consale instead"; strictly speaking printStackTrace() would accomplish exactly that. I just didn't make the same mental leap to best practices.