Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

185
Vistas
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?

about 4 years ago · Santiago Trujillo
3 Respuestas
Responde la pregunta

0

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/

about 4 years ago · Santiago Trujillo Denunciar

0

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);
            }
        }
    });
}
about 4 years ago · Santiago Trujillo Denunciar

0

In this scenario, you need to handle "MethodArgumentTypeMismatchException" you can do that using @ControllerAdvice

about 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda