Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to customize the error message for NoSuchElementException in Optional class

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.

like image 538
Georgi Michev Avatar asked Oct 18 '25 21:10

Georgi Michev


2 Answers

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.");
like image 180
Peter Walser Avatar answered Oct 21 '25 10:10

Peter Walser


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.") );
like image 40
L.Spillner Avatar answered Oct 21 '25 10:10

L.Spillner



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!