4

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.

3

3 Answers 3

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); } } 
Sign up to request clarification or add additional context in comments.

2 Comments

Are you returning a View or ResponseBody? This will return a response body, not a view.
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.
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); 

Comments

-1

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

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

1 Comment

How will you catch the exception if the problem is a mismatch between the parameter type and the type supplied by the incoming request?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.