Reputation: 24706
In my Spring MVC controller I have a method like this:
public String myMethod(@RequestParam(defaultValue="0") int param) { ... }
When I pass a string as value of my param
I'm obviously getting a NumberFormatException
:
Failed to convert value of type 'java.lang.String' to required type 'int'; nested exception is java.lang.NumberFormatException: For input string: "test"
That's clear...
So I'm trying to find a way to redirect user to a default page when this error is occurring. Is there a common way to achieve this?
At the moment I'm thinking about using a String
in place of an int
to map my param
, check if this is parsable to int
and then switch to the appropriate logic, but this seems a workaround, not a solution...
Is there a more elegant way to handle this problem and keep the correct type binding for my param
?
Upvotes: 6
Views: 3961
Reputation: 9
In this scenario, you need to handle "MethodArgumentTypeMismatchException" you can do that using @ControllerAdvice
Upvotes: -1
Reputation: 79
Please have a look into the @Valid annotation. Hope this helps. This annotation helps in adding more validations for the request parameter.
https://spring.io/guides/gs/validating-form-input/
Upvotes: 1
Reputation: 24706
I finally solved adding a CustomNumberEditor
like this:
@InitBinder
public void registerNumbersBinder(WebDataBinder binder) {
binder.registerCustomEditor(Integer.class, new CustomNumberEditor(Integer.class, true){
@Override
public void setAsText(String text) throws IllegalArgumentException {
try{
super.setAsText(text);
}catch (IllegalArgumentException ex){
setValue(0);
}
}
});
}
Upvotes: 2