How to customize database unique constraint error message in JSF
<p>I have a Name with a UNI constraint, and when a user registers a duplicate name, it throws an exception:</p>

<pre><code>Caused by: java.sql.SQLIntegrityConstraintViolationException: Duplicate entry 'John' for key 'UK_t622yodh32su1s2wseebkimwp'
</code></pre>

<p>In the JSF view page, the exception caught by the exception handler is displayed to the user:</p>

<pre><code>Duplicate entry 'John' for key 'UK_t622yodh32su1s2wseebkimwp'
</code></pre>

<p>Code:</p>

<pre><code>public void register (Student student) {
   ...

catch (Exception e) {
            String errorMessage = getRootErrorMessage(e);
            FacesMessage m = new FacesMessage(FacesMessage.SEVERITY_ERROR, errorMessage, "Registration unsuccessful");
            facesContext.addMessage(null, m);
        }
}

private String getRootErrorMessage(Exception e) {

        String errorMessage = "Registration failed.";
        if (e == null) {
            return errorMessage;
        }

        Throwable t = e;
        while (t != null) {
            errorMessage = t.getLocalizedMessage();
            t = t.getCause();
        }

        return errorMessage;
    }
</code></pre>

<p>Registration.xhtml:</p>

<pre><code>&lt;p&gt;
            &lt;h:panelGrid columns="2"&gt;
                &lt;h:commandButton id="register"
                    action="#{registrationController.register(registrationView.student)}" value="Register"
                    styleClass="register" /&gt;
                &lt;h:messages styleClass="messages" errorClass="invalid"
                    infoClass="valid" warnClass="warning" globalOnly="true" /&gt;
            &lt;/h:panelGrid&gt;
        &lt;/p&gt;
</code></pre>

<p>The problem here is that, it only displays the exception error code, as above. I would like to the error message something like:</p>

<pre><code>The user name has been registered, Please use another one. Thanks.
</code></pre>

<p>This is more user friendly, compared to the SQL constraint violation error message. How to achieve this?</p>