For your particular use case, you can use @ExceptionHandler in the Controller or in a @ControllerAdvice class as shown here. For example, I am returning NOT_FOUND error for the sake of it.
@ExceptionHandler({MethodArgumentTypeMismatchException.class})
@ResponseStatus(value = HttpStatus.NOT_FOUND, reason = "this is the reason")
public void handle() {
}
You may not see the reason in the actual error response, until you enable
server:
error:
include-message: always
If you think your @ExceptionHandler is only needed in a Controller class you can keep the method inside the controller. Alternatively you can create a @ControllerAdvice class and put the method there, so that you can reuse across multiple controllers in your application.
However, if you want a more complex validation, I will suggest to keep the id type to String and then cast manually into Long and perform the validation. Doing so you can throw your own RuntimeException and handle different cases.