2

I have simple spring controller.

@GetMapping("/test")
@ResponseBody
public String doSomething(@RequestParam int a) {

    return String.valueOf(a);
}

when i pass a=1 in query string it works fine.

but when i pass a=abc it gave me this.

> Failed to convert value of type 'java.lang.String' to required type
> 'int'; nested exception is java.lang.NumberFormatException: For input
> string: "abc".

is there a way so i can handle this error and response back to user like a must be numeric.

thanks in advance.

Youcef LAIDANI
  • 55,661
  • 15
  • 90
  • 140
cool cool
  • 247
  • 2
  • 12
  • It's called JSR-303/JSR-349 Bean Validation : https://docs.spring.io/spring/docs/current/spring-framework-reference/html/validation.html – AchillesVan Aug 01 '17 at 15:08

3 Answers3

0

You can use @ControllerAdive to handle such exceptions.

@ControllerAdvice
public class RestControllerAdive extends ResponseEntityExceptionHandler 
{
    @ExceptionHandler(value=NumberFormatException.class)
    public ResponseEntity<Object> handleNumberFormatException(NumberFormatException ex)
    {
        return new ResponseEntity({your-error-message}, HttpStatus);
    }
}
Rana_S
  • 1,520
  • 2
  • 23
  • 39
  • Are you returning a `View` or `ResponseBody`? This will return a response body, not a view. – Rana_S Aug 01 '17 at 15:27
  • you don't have extend from ResponseEntityExceptionHandler, and ControllerAdvice works only when the exception is thrown within the action method but converters are called before that. – Next Developer May 24 '18 at 16:53
0

I got Two ways: 1. Using Spring ExceptionHandler

@ExceptionHandler({Exception.class})
public ModelAndView handleException(Exception exception) {
ModelAndView modelAndView = new ModelAndView("Exception");
modelAndView.addObject("exception", exception.getMessage());
return modelAndView;
}
  1. Instead of int, use String.

    public String doSomething(@RequestParam String a) { // conversion to int; validations & Exception handling logic will come here return String.valueOf(a); }

we follow in this way. we have a utility class, which will have all conversion and validation logic. each time we just have to call respective method. like:

UtilityClass.isValidInt(a);
UtilityClass.isValidLong(a);
Mohammad
  • 11
  • 3
-1

The elegant solution for that is catching the Exception and then, use the "ResponseEntity" like this answer:

https://stackoverflow.com/a/16250729/2520689

pakkk
  • 289
  • 1
  • 2
  • 13
  • How will you catch the exception if the problem is a mismatch between the parameter type and the type supplied by the incoming request? – laim2003 Dec 12 '20 at 22:43