Spring web data binders : override default error message

When binding a HTML form to a Java bean using Spring technology, you may have type conversions issues that will display an ugly error message.

For instance, you have an input that binds to a BigDecimal attribute in a Java bean.

<form:form modelAttribute="myBean" action="${submitURL}" method="post">
  <form:input path="myBigDecimalProperty" value="${myBean.myBigDecimalProperty}" />
  <button type="submit">Submit</button>

If you type in letters in your input and you submit the form, the following error will be displayed :

Failed to convert property value of type java.lang.String to required type java.math.BigDecimal for property myBigDecimalProperty; nested exception is java.lang.IllegalArgumentException: Could not parse number: Unparseable number: “thisisnotabigdecimalvalue”

If a user see that kind of error, he will throw his computer through the window and claim he has been attacked by north korean hackers.

You should solve that issue by adding new messages in a resource bundle file :

For a specific type :

typeMismatch.java.math.BigDecimal=Only numbers are allowed!

For a specific Java property :

typeMismatch.myBigDecimalProperty=The field ‘myBigDecimalProperty’ should be a number.

Have a look to this piece of documentation to understand how error messages are built : http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/validation/DefaultMessageCodesResolver.html

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.