Video in progress

Strong Junior 🌱 Spring

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:

  1. GET /users: no age. @RequestParam is required = true by default, Spring throws MissingServletRequestParameterException and returns 400 Bad Request. The method isn't called.
  2. GET /users?age=abc: a String can't be converted to int, so MethodArgumentTypeMismatchException, again 400.
  3. 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.