Inside a REST API request json body, I'm passing "argument1":true and it works. But I discovered that when using any number it converts it to true. Only when using explicitly false it turns into false. I'm using Spring Boot ResponseEntityExceptionHandler and @RestControllerAdvice to handle all exceptions. How can I cast any exception when converting 534 to true?
1 Answer
Add in your controller a method annotated with @InitBinder and provide a custom boolean editor
@InitBinder
public void initBinder(WebDataBinder webDataBinder) {
webDataBinder.registerCustomEditor(Boolean.class, new CustomBooleanEditor("true", "false", false));
}
Spring registers a default CustomBooleanEditor mapping "true", "on", "yes" and any non zero number as true (also allowing empty value as false) throwing IllegalArgumentException when value is not valid.
You can either override it or provide your own implementation throwing a specific exception.
3 Comments
gabriel119435
Thanks for your info. Could you please link any documentation towards this information? Thanks in advance
noiaverbale
It's not a much, but InitBinder. Can't find a list of default converters/editor right now.
poyger
I don't get this working when having a @RequestBody.....so it is no forms just a rest endpoint.....should it work in that scenario also ?
argument1to be of type boolean or int? I mean, you want spring binder to throw exception whenargument1is integer and not boolean?