title: Database - handling of unique constraint violation
body: <p>I have a user creation screen that takes various user details along with first name and mobile number.  I have a corresponding USER table in which the First Name and the Mobile number form a composite unique key.  There are other integrity constraints defined on this table as well.</p>
  
  <p>When user data is entered on the Create User screen that violates this constraint, user needs to be shown an 'user friendly' error message.</p>
  
  <p>When such a violation occurs, the exception that I get from the MySQL database is:</p>
  
  <pre><code>com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Duplicate entry '1-1' for key `uk_FIRST_NAME__MOBILE_idx`
  </code></pre>
  
  <p>There are two options to show a meaningful message (for example: "ERROR: User name already exists for the given mobile number, please change either one of them").</p>
  
  <p>Option 1: In the catch block of this exception, parse the MySQL exception's message and look for 'uk_FIRST_NAME__MOBILE_idx'.  If present, show the user friendly message as mentioned above.</p>
  
  <p>Option 2: Write a DAO level API that will take first name and mobile number as the only two parameters, fire a database query to see if there is an existing record matching this first name/mobile combination.  If true, show the error message to the user; else, run an insert query to insert the user of record into the USER table.</p>
  
  <p>I do NOT like the option 1, as it needs me to 'parse' the exception message, which is not a clean solution.  I do NOT like the Option 2 as well, as it needs me to run 'two queries' on the database which is less efficient than the option 1, which is a single query solution.</p>
  
  <p><strong>Question:</strong> Are there any other options which are better than these two?  If not, which one is the right approach among the above two?</p>