Reputation: 3556
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
Reputation: 13702
Spring will fail with an 500
status code, because it cannot parse the value.
The stages of request handling are:
@Validated
is used 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 Date
s), 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