I have a method that throws NotFoundException
if my object id is null
.
public void removeStatementBundleService(String bundleId) throws NotFoundException {
Optional<StatementBundle> bundleOpt = statementBundleRepository.findById(bundleId);
if(bundleOpt.isPresent()) {
StatementBundle bundle = bundleOpt.get();
if(bundle.getStatements() != null && !bundle.getStatements().isEmpty()) {
for(Statement statement: bundle.getStatements()) {
statementRepository.delete(statement);
}
}
if(bundle.getFileId() != null) {
try {
fileService.delete(bundle.getFileId());
} catch (IOException e) {
e.printStackTrace();
}
}
statementBundleRepository.delete(bundle);
} else {
throw new NotFoundException("Statement bundle with id: " + bundleId + " is not found.");
}
}
I found out that this isn't needed since the java.util.Optional
class is used. In the oracle documentation I found out that if get()
is used and there is no value then NoSuchElementException
is thrown. What is the best way I can add my error message to the exception. I am trying to open the Optional
class in Eclipse to try change inside it(not sure if this is good practice) but Eclipse will not let me access this class on the other hand I read that this class is also final.
When resolving the Optional value
, you can directly throw an Exception if the value is not present:
Optional<StatementBundle> bundleOpt = statementBundleRepository.findById(bundleId);
StatementBundle bundle = bundleOpt.orElseThrow(()
-> new NotFoundException("Statement bundle with id: " + bundleId + " is not found.");
or (single statement):
StatementBundle bundle = statementBundleRepository.findById(bundleId)
.orElseThrow(()
-> new NotFoundException("Statement bundle with id: " + bundleId + " is not found.");
The Optional
class does provide a orElseThrow(...)
method which takes a Supplier
as it's only parameter and therefore allowing us to throw custom exception in case the value is absent.
This enables expressions like:
StatementBundle bundle = bundleOpt.orElseThrow( ()->new NotFoundException("Statement bundle with id: " + bundleId + " is not found.") );
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