Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Avoid NumberFormatException in Spring MVC controller

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?

like image 530
davioooh Avatar asked Apr 10 '17 13:04

davioooh


2 Answers

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);
            }
        }
    });
}
like image 76
davioooh Avatar answered Oct 06 '22 04:10

davioooh


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/

like image 25
VijayC Avatar answered Oct 06 '22 02:10

VijayC