0

I am working on an spring restful endpoint which accepts page range(start & end page number). I want my request params- pageStart and pageEnd to accept only integers. When I pass 'pageStart = a' through postman I get below error:

    @RequestMapping(value = "/{accNumber}/abc/xyz", method = RequestMethod.GET)
    @Loggable
    @ResponseBody
    public RestResponse<Class1> getData(
        @Loggable @PathVariable(value = "accNumber") String accNumber,
        @RequestParam(value = "pageStart", required = false, defaultValue = "0") Integer pageStart,
        @RequestParam(value = "pageEnd", required = false, defaultValue = "10") Integer pageEnd,
        HttpServletResponse response) throws Exception {

    Class1 class1 = new Class1();
    class1 = retrieveData(accNumber, pageStart, pageEnd);
    RestResponse<Class1> restResponse = new RestResponse<Class1>(
            class1);

    return restResponse;
    }

The request is not valid [Failed to convert value of type 'java.lang.String' to required type 'java.lang.Integer'; nested exception is java.lang.NumberFormatException: For input string: \"a\"]

How do I handle this exception and let the user know that he should pass only integers?

Tharsan Sivakumar
  • 6,351
  • 3
  • 19
  • 28
Deepa
  • 41
  • 1
  • 9

1 Answers1

1

You can handle it in two ways

1) Using exception handler method

Have a method in the controller

@ExceptionHandler({Exception.class})
    public ModelAndView handleException(Exception ex) {
        ModelAndView model = new ModelAndView("Exception");

        model.addObject("exception", ex.getMessage());

        return model;
    }

http://www.codejava.net/frameworks/spring/how-to-handle-exceptions-in-spring-mvc

2) Use String parameter

Use String as the type for all @PathVariable and @RequestParameter parameters then do the parsing inside the handler method.

Tharsan Sivakumar
  • 6,351
  • 3
  • 19
  • 28
  • Thanks, @TharsanSivakumar First option would help fix this issue. But considering the second option, if I set my request param to be String, then it would accespt just anything. I want my endpoint to accept only integers as it is page range. How do I go about this? – Deepa Mar 29 '17 at 06:29
  • Then go with the 1st option and you can get more info in the provided link – Tharsan Sivakumar Mar 29 '17 at 06:32
  • error in postman: { "errors": [ { "code": "service.badRequest", "description": "The request is not valid [Failed to convert value of type 'java.lang.String' to required type 'java.lang.Integer'; nested exception is java.lang.NumberFormatException: For input string: \"a\"]" } ] } – Deepa Mar 29 '17 at 08:23