Question

I've been trying to add custom messages for validation errors for a REST Service managed by Spring MVC within a @Controller class.

The Employee class:

public class Employee {

    @NotNull
    @NotEmpty
    private String company;
    ...
}

My REST Service:

@ResponseStatus(value = HttpStatus.CREATED)
@RequestMapping(method = RequestMethod.POST)
public void add(@RequestBody @Valid Employee employee) {
    employees.add(employee);
}

And the validation errors parses

@ResponseStatus(value = HttpStatus.BAD_REQUEST)
@ExceptionHandler(MethodArgumentNotValidException.class)
public @ResponseBody
List<String> validationExceptions(MethodArgumentNotValidException e) {
    List<String> errors = new ArrayList<String>();

    for (FieldError error : e.getBindingResult().getFieldErrors()) {
        errors.add(error.getDefaultMessage());
    }

    return errors;
}

So I've put a ValidationMessages.properties on the root of my classpath, and I'm not able to get my custom messages with the following key NotEmpty.employee.company.

I know there are many ways to do this with a ResourceBundle and error.getCode(), or even with the key org.hibernate.validator.constraints.NotEmpty.message, but I'd like have specific messages to specific field of specific objects.

I also don't want to do this with @NotEmpty(message = "NotEmpty.employee.company}"). I want it the simplest.

What should I do?

No correct solution

OTHER TIPS

Have you tried to implement your own

org.springframework.validation.MessageCodesResolver

and then declaring your implementation in the config file:

<mvc:annotation-driven message-codes-resolver="org.example.YourMessageCodesResolverImpl"/>

I'd give it a try, it seems this one is able to build custom error codes like the ones you want:

String[]    resolveMessageCodes(String errorCode, String objectName, String field, Class<?> fieldType)

The only and important thing I'm not sure is whether it'll override the error codes generated by the hibernate validators...

I hope it helps (and works).

Cheers,

Chico.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top