Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

186
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório

0

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

about 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda