Ctorres
Ctorres

Reputation: 476

How can I prevent a null RequestParam raising an exception?

I'm working in a Spring Boot environnement using Kotlin. I made a controller with a method annotated with @GetMapping. This method have some parameters of type @RequestParam declared as Double type. If I try to call my method without providing these parameters, my code raises the following exception:

java.lang.IllegalStateException: Optional double parameter 'latitude' is present but cannot be translated into a null value due to being declared as a primitive type.

I assume that the parameters have default value (probably 0.0), but Kotlin need an object which can be null, so the exception is raised.

All works fine if I provide the parameters, but I want my code working if no parameters are provided.

How can I avoid this exception?

Here's how my controller looks like:

@RestController
@RequestMapping("/api/stations")
class StationController {

    @GetMapping
            fun findAll(@RequestParam(value = "latitude", required = false) currentLatitude: Double,
                        @RequestParam(value = "longitude", required = false) currentLongitude: Double): ResponseEntity<List<Entity>> {
                //Method body
            }

Upvotes: 3

Views: 2289

Answers (1)

Roland
Roland

Reputation: 23312

Maybe the following part of the documentation regarding basic types will help you:

On the Java platform, numbers are physically stored as JVM primitive types, unless we need a nullable number reference (e.g. Int?) or generics are involved. In the latter cases numbers are boxed.

Your guess might be correct then. Try using Double? and it should be ok.

Upvotes: 3

Related Questions