Soumitri Pattnaik
Soumitri Pattnaik

Reputation: 3556

How to validate request parameters in Spring REST controller

I am working on a Spring REST application.
This application has only REST controllers, no view part.

I want to know how can I validate a @RequestParam

For example

@RequestMapping(value = "", params = "from", method = RequestMethod.GET)
    public List<MealReadingDTO> getAllMealReadingsAfter(@RequestParam(name = "from", required = true) Date fromDate) {
......
......
}

In the above example, my goal is to validate the Date. Suppose someone pass an invalid value, then I should be able to handle that situation.
Now it is giving and exception with 500 status.

PS
My question is not just about Date validation.
Suppose, there is a boolean parameter and someone passes tru instead of true by mistake, I should be able to handle this situation as well.

Thanks in advance :)

Upvotes: 1

Views: 6412

Answers (1)

Matyas
Matyas

Reputation: 13702

Spring will fail with an 500 status code, because it cannot parse the value.

The stages of request handling are:

  1. receive request
  2. identify endpoint
  3. parse request params / body values and bind them to the detected objects
  4. validate values if @Validated is used
  5. enter method call with proper parameters

In your case the flow fails at the parse (3) phase.

Most probably you receive a BindException. You may handle these cases by providing an exception handler for your controller.

@ControllerAdvice
public class ControllerExceptionHandler {
     @ExceptionHandler(BindException.class)
     @ResponseStatus(HttpStatus.BAD_REQUEST)
     @ResponseBody
     public YourErrorObject handleBindException(BindException e) {
         // the details which field binding went wrong are in the 
         // exception object. 
         return yourCustomErrorData;
     }
}

Otherwise when parsing is not functioning as expected (especially a hussle with Dates), you may want to add your custom mappers / serializers.

Most probably you have to configure Jackson, as that package is responsible for serializing / deserializing values.

Upvotes: 3

Related Questions