0

Suppose I have a RestController for a @GetMapping as below

ResponseEntity<?> getXXX(
@RequestParam(value = "param1", required = true) String param1,
@RequestParam(value = "param2", required = true) String param1)

if consumer performs @Get for this API without param1 and param2, Spring will throw the "MissingServletRequestParameterException" but only for the param1 but param2

My question here is if consumer doesn't pass both param1 and param2, could we somehow get MissingServletRequestParameterException for both param1 and param2?

Please advice me

Nghia Do
  • 2,588
  • 2
  • 17
  • 31

1 Answers1

0

First of all, this code won't compile since you have redeclared a variable within a scope. Moreover, if I understood the question correctly, if you refactor the given snippet of code (so that it compile), spring will throw an exception when notice the first required parameter is missing just like jvm throws NullPointerException in analogous situation with information about exception only in line with exception:

String a = null;
String b = null;
a.length();      //NullPointerException exception thrown
b.length();

You have to create your custom validator checking if parameters were given in request and if not, throw an appropriate exception. Something like:

void validate(String param1, String param2) {
        Stream.of(param1, param2).filter(Objects::nonNull).findAny().orElseThrow(() -> new IllegalArgumentException("param1 and param2 are missing"));
        Optional.ofNullable(param1).orElseThrow(() -> new IllegalArgumentException("param1 is missing"));
        Optional.ofNullable(param2).orElseThrow(() -> new IllegalArgumentException("param2 is missing"));
    }

with an exception you'd like to throw. If you want to do it this way, set values of "required" flags to false.

dev123
  • 477
  • 8
  • 20
  • 1
    1. Better do not use abbrevations when you are answering the question, there is a possibility that somebody will not decode it. 2. I would suggest to use `Optional` class for `null` checks. Java 8 advent was quite some time ago. – DevDio Oct 13 '17 at 18:01
  • 1
    Thanks. The code is not actual code, I just type it for the question. – Nghia Do Oct 13 '17 at 19:49