Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to personalise message for data conversion failure in Spring MVC?

Tags:

spring-mvc

I have a Spring MVC web application as follows:

@Controller
@RequestMapping("/users")
public class UserController extends FrontEndController {

    @RequestMapping(method = RequestMethod.POST)
    public String post(@Valid @ModelAttribute("user") User user, Errors errors, Model model) {
        ...
    }
}

class User {
    @NotBlank(message = "user name is mandatory")
    String userName;

    public enum Color {RED, GREEN, YELLO}

    @NotNull(message = "color is mandatory")
    private Color color;
    // getters and setters
}

When my web controller validates User, it tells "color is mandatory" if this parameter has not been specified. This message is shown in the web form. However, if the string "BLUE" is passed to color (which is not one of the 3 enum options), I get a message as follows:

Failed to convert property value of type java.lang.String to required type User$Color for property color; nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type java.lang.String to type @javax.validation.constraints.NotNull User$Color for value BLUE; nested exception is java.lang.IllegalArgumentException: No enum constant User.Color.BLUE.

This message is shown in the web form.

As pointed out by How to personality error message for hibernate validator enum? this message does not have anything to do with validator; this message is created before the validator is run. Spring tries to convert the string "BLUE" to the enum, and so it fails and generates this message.

So, how can I tell Spring MVC to personalise this message? Instead of "Failed to convert property value of type java.lang.String to...", I'd like to say something simple as "invalid color".

like image 914
David Portabella Avatar asked Jul 08 '14 13:07

David Portabella


1 Answers

You can define these messages in the same .properties files where you define your messages for Spring MVC internationalization/localization (and you can localize them too). It applies to both: validation (JSR-303) and data binding (data conversion) errors.

The format of the messages is described here.

This question explains how to configure a resource bundle (it's all you need to define messages in English). Implementing internationalisation will take some further configuration. See the Externalization and Internationalization section in this tutorial.

like image 50
Alexey Avatar answered Sep 25 '22 14:09

Alexey