Video in progress
What response does the client get if a request to this endpoint is sent without the age parameter, or with age=abc?
@GetMapping("/users")
List<UserDto> search(@RequestParam int age) {
return service.findByAge(age);
}
If age is missing, the required parameter is absent, so 400. If abc comes in, it can't be converted to int, so again 400. But if you make it required = false and leave the type as primitive int, a request without the parameter gives 500.
📖 Answer
Let's separate three cases:
GET /users: noage.@RequestParamisrequired = trueby default, Spring throwsMissingServletRequestParameterExceptionand returns400 Bad Request. The method isn't called.GET /users?age=abc: aStringcan't be converted toint, soMethodArgumentTypeMismatchException, again400.- Someone says "let the parameter be optional" and writes this:
List<UserDto> search(@RequestParam(required = false) int age)
Now if age is missing, Spring can't give a null value to a primitive int and returns 500 with an IllegalStateException. It was a client mistake, but it turned into a server error.
The right variants:
@RequestParam(required = false) Integer age // can be null
@RequestParam(defaultValue = "18") int age // with a default
@RequestParam Optional<Integer> age // Optional
In a global @RestControllerAdvice, return a clear response for these two exceptions, so the client sees what went wrong. Spring 6's default ProblemDetail response may be enough for this too.
Sign up to mark studied questions and save your progress.