Announcement Announcement Module
Collapse
No announcement yet.
<form:errors> and nested exceptions Page Title Module
Move Remove Collapse
X
Conversation Detail Module
Collapse
  • Filter
  • Time
  • Show
Clear All
new posts

  • <form:errors> and nested exceptions

    Is there a way to replace nested exceptions in an Errors or BindingResult object with a localized "friendly" error message?

    Some info:

    I do some validation in one of my domain objects to ensure that usernames don't have any fewer than 6 characters by throwing an IllegalArgumentException in the setUserName() method. I'm aware of the Validator interface, which I use for other of my domain objects but it wasn't appropriate in this case.

    On the web side of things, when a new user is created with a username fewer than 6 characters, the following appears in my <form:errors />

    Code:
    Property username threw exception; nested exception is java.lang.IllegalArgumentException: A username must contain at least six characters.
    While I'm happy that the exception is associated with the appropriate field and included in the Errors object, this isn't very helpful for an end user. Is there a way to "trap" this error and replace it with a friendlier, localized error?

  • #2
    I found the solution, thanks to this extremely helpful post:

    http://forum.springframework.org/showthread.php?t=57281

    I'm not sure why this isn't in the manual, but any of the "Codes" in an ErrorObject (which can be retrieved using getCodes() ) can be placed in errors.properties to override the unfriendly error messages with localized friendly versions.

    In my case, this worked out to:

    methodInvocation.user.userName=A username must contain at least six characters.

    Easy as pie! At least, once you know how.

    Comment

    Working...
    X