Is it possible to add a custom message to an enum if validation fails?
I have this enum class:
public enum MyEnum{
foo('F'),
bar('B'),
qux('Q');
private char id;
EngineType(char id) {
this.id = id;
}
public char getId() {
return this.id;
}
}
My model class contains private MyEnum myEnum;
.
Currently if a value is passed in which isn't a valid enum, I get this BindingException:
{
"status": 400,
"validationErrors": {
"myEnum": "Failed to convert property value of type 'java.lang.String' to required type 'ie.aviva.services.motor.cartellservice.model.EngineType' for property 'myEnum'; nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type [java.lang.String] to type [@javax.validation.constraints.NotNull ie.aviva.services.motor.cartellservice.model.EngineType] for value 'corge';"
},
"title": "Bad Request"
}
My controller looks like this:
@RequestMapping(
method = RequestMethod.GET,
value = Endpoints.TRUE_MATCH,
produces = {"application/json"})
public ResponseEntity<ResponseWrapper<List<TrueMatch>>> getTrueMatch(
@Valid MyDetails MyDetails) {
LogContext.put(Constants.TAG, myDetails);
LOG.info(
"Controller called to get true match with my details: " myDetails.toString());
...
}
MyDetails is like this:
@NoArgsConstructor
@AllArgsConstructor
@Getter
@Setter
@SuperBuilder
public class MyDetails extends BasicDetails {
@NotBlank
@Pattern(
regexp = "^[a-zA-Z]*$",
message = "'${validatedValue}' contains unsupported characters")
private String name;
@NotNull private MyEnum myEnum;
...
}
Is it possible to change the message to some custom message of my own? I'm already able to do this in annotations that I added to other variables by including the message
parameter in the annotation. I tried creating an annotation to validate the pattern as seen
- Invalid request: