Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<ol> <li><p>The question is not really related to checked vs. unchecked debate, the same applies to both exception types.</p></li> <li><p>Between the point where the ConstraintViolationException is thrown and the point, where we want to handle the violation by displaying a nice error message is a large number of method calls on the stack that should abort immediately and shouldn't care about the problem. That makes the exception mechanism the right choice as opposed to redesigning the code from exceptions to return values.</p></li> <li><p>In fact, using an unchecked exception instead of a checked exception is a natural fit, since we really want all intermediate methods on the call stack to <em>ignore</em> the exception and <em>not handle it</em> .</p></li> <li><p>If we want to handle the "unique name violation" only by displaying a nice error message (error page) to the user, there's not really a need for a specific DuplicateUsernameException. This will keep the number of exception classes low. Instead, we can create a MessageException that can be reused in many similar scenarios.</p> <p>As soon as possible we catch the ConstraintViolationException and convert it to a MessageException with a nice message. It's important to convert it soon, when we can be sure, it's really the "unique user name constraint" that was violated and not some other constraint.</p> <p>Somewhere close to the top level handler, just handle the MessageException in a different way. Instead of "we logged your problem but for now you're hosed" simply display the message contained in the MessageException, no stack trace.</p> <p>The MessageException can take some additional constructor parameters, such as a detailed explanation of the problem, available next action (cancel, go to a different page), icon (error, warning)...</p></li> </ol> <p>The code may look like this</p> <pre><code>// insert the user try { hibernateSession.save(user); } catch (ConstraintViolationException e) { throw new MessageException("Username " + user.getName() + " already exists. Please choose a different name."); } </code></pre> <p>In a totally different place there's a top exception handler</p> <pre><code>try { ... render the page } catch (MessageException e) { ... render a nice page with the message } catch (Exception e) { ... render "we logged your problem but for now you're hosed" message } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload