Hi all, got a spring/kotlin specific question. Wha...
# spring
k
Hi all, got a spring/kotlin specific question. What is the best way to deal with parameters that might be nullable in some controllers and non null in others? For example; I’ve written a converter for the
CountryCode
which converts a String to a CountryCode. If this value is not there or invalid it will return a 400 “InvalidParameter”. But if I make the value nullable, the value should just be null when it’s missing or invalid.
Copy code
@RequestParam(value = "country") countryCode: CountryCode // Should throw an exception when invalid or missing
@RequestParam(value = "country") countryCode: CountryCode? // Should be null when invalid or missing
Is there a way to create separate converters for the nullable and non nullable implementations? (Probably not because it’s not actually a different type?) By just returning null in the converter I will get:
Copy code
Required request header 'country' for method parameter type CountryCode is present but converted to null
Which feels like its leaking some information to the outside world which they don’t need to know about. I could make the param an
Optional<CountryCode>
for the nullable case, map the message of the exception or do the mapping from String to CountryCode in the controller function. But those options all feel less nice. Is there a completely different solution I didn’t think of?
n
i think you’re making it overcomplicated i’d suggest KISS always use this:
@RequestParam(value = "country") countryCode: CountryCode?
and then throw explicitly that will more maintainable for the next developers
k
sad days, was afraid that would be the only solution
Thanks!
t
you could also have a
@RestControllerAdvice
where you convert kotlin binding exception into a 400 (I am not sure which exception is thrown by kotlin when binding fails)
Copy code
@RestControllerAdvice
class ExceptionAdvice : ResponseEntityExceptionHandler() {

  @ExceptionHandler(
    value = [
      KotlinException::class,
    ]
  )
  fun handleClientException(ex: KotlinException) = convert exception to meaningful 400 here
}

@RequestParam(value = "country") countryCode: CountryCode // when input is null, this would throw
@RequestParam(value = "country", required=false) countryCode: CountryCode? // when null, this would not throw
👀 1
t
I’d use the required flag and defaults as necessary. If a required parameter is not present, spring will throw a
MissingServletRequestParameterException
and return a 400 bad request (which you can customize in an @ExceptionHandler or controller advice if necessary — but that default makes sense)