Kilian Steenman
10/18/2021, 5:11 PMCountryCode
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.
@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:
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?nfrankel
10/18/2021, 7:07 PM@RequestParam(value = "country") countryCode: CountryCode?
and then throw explicitly
that will more maintainable for the next developersKilian Steenman
10/19/2021, 5:33 AMKilian Steenman
10/19/2021, 5:33 AMthanksforallthefish
10/19/2021, 7:27 AM@RestControllerAdvice
where you convert kotlin binding exception into a 400 (I am not sure which exception is thrown by kotlin when binding fails)
@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
Tom Hermann
11/01/2021, 2:52 PMMissingServletRequestParameterException
and return a 400 bad request (which you can customize in an @ExceptionHandler or controller advice if necessary — but that default makes sense)