I have some code where I'm using Java 8 Optional
in which I want to log
an error when I don't get the required result.
As shown in following Example I have commented
on a line where I get the error when I'm trying to log Error Message
:
@PutMapping("/organs/{id}")
public Organ updateorgan(@PathVariable(value = "id") Long organId,
@Valid @RequestBody Organ organDetails) {
Organ organ = organRepository.findById(organId)
.orElseThrow(() ->
// LOG.log(Level.SEVERE,"Organ with id "+organId + "not found");
new ResourceNotFoundException("organ", "id", organId)
);
organ.setName(organDetails.getName());
Organ updatedOrgan = organRepository.save(organ);
LOG.info("Updated organ details. Response :"+updatedOrgan);
return updatedOrgan;
}
P.S - I only want to use the Java 8
method and not conventional approach.
Thanks in advance!
Optional object is used to represent null with absent value. This class has various utility methods to facilitate code to handle values as 'available' or 'not available' instead of checking null values. It is introduced in Java 8 and is similar to what Optional is in Guava.
Optional is a container object which may or may not contain a non-null value. You must import java. util package to use this class. If a value is present, isPresent() will return true and get() will return the value.
The are three creational methods for creating an optional instance. Returns an empty Optional instance. Optional<String> empty = Optional. empty();
Make it a lambda with a body enclosed by curly braces and a return
statement instead of an expression lambda:
Organ organ = organRepository.findById(organId)
.orElseThrow(() -> {
LOG.log(Level.SEVERE,"Organ with id "+organId + "not found");
return new ResourceNotFoundException("organ", "id", organId);
});
You have to use return
Organ organ = organRepository.findById(organId)
.orElseThrow(() -> {
LOG.log(Level.SEVERE,"Organ with id "+organId + "not found");
return new ResourceNotFoundException("organ", "id", organId);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With