Reputation: 5749
I use Optional in a controller
@GetMapping(value = "/address/{id}")
public ResponseEntity<Addresses> getAddressById(@PathVariable("id") Integer id) {
Optional<Address> address = addressService.getAddressById(id);
return new ResponseEntity(address.get(), address.isPresent() ? HttpStatus.OK : HttpStatus.NOT_FOUND);
}
Actually, if there is no value, i get
java.util.NoSuchElementException: No value present
at java.util.Optional.get(Optional.java:135) ~[na:1.8.0_131]
not sure if it's a good way to manage thing.
is there any good pratice
Upvotes: 1
Views: 2401
Reputation: 5103
You're missing the fluent quality of Optionals. Think of them like a Stream:
@GetMapping(value = "/address/{id}")
public ResponseEntity<Address> getAddressById(@PathVariable("id") Integer id) {
return addressService.getAddressById(id)
.map(ResponseEntity::ok)
.orElse(new ResponseEntity<Address>(NOT_FOUND));
}
Upvotes: 7
Reputation: 234807
Try this:
return address.isPresent()
? new ResponseEntity(address.get(), HttpStatus.OK)
: new ResponseEntity(HttpStatus.NOT_FOUND);
With your current code, you are calling address.get()
regardless of whether or not a value is present.
Note that for a more informative NOT_FOUND
response (response code 404), you probably should still include a body in the response (which my suggested code does not do). From the HTTP spec (RFC 7231) section on 4xx response codes:
Except when responding to a HEAD request, the server SHOULD send a representation containing an explanation of the error situation, and whether it is a temporary or permanent condition.
According to RFC 2119, the key word "SHOULD" means:
that there may exist valid reasons in particular circumstances to ignore a particular item, but the full implications must be understood and carefully weighed before choosing a different course.
Upvotes: 9