How to customize the error message for NoSuchElementException in Optional class

the return value of orelsethrow'' must be used
optional throw exception
java exception supplier

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.");

Throw Exception in Optional in Java 8, Explore how to throw an exception from Java 8 Optional. GO. Start Here; Courses ▽△ I just announced the new Learn Spring course, focused on the In this tutorial, we're going to show how to throw a custom exception when an Optional is empty. Otherwise, it throws NoSuchElementException. The NoSuchElementException is thrown by an Enumeration's nextElement method which indicates that there are no more elements left in the enumeration. The NoSuchElementException is thrown by the following methods- The NoSuchElementException is a subclass of RuntimeException and implements the Serializable interface.

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.") );

26 Reasons Why Using Optional Correctly Is Not Optional, This is a suite of items that try to address Optional in your code NoSuchElementException Exception Via orElseThrow() Since Java 10 The Optional class is definitively not intended for use as a property of a Java Bean. Java 14 is not supported, yet, so we want to manually configure a few things. public class NoSuchElementException extends RuntimeException. Thrown by various accessor methods to indicate that the element being requested does not exist. Enumeration.nextElement (), Iterator.next (), Serialized Form. Constructor Summary. Constructor and Description. NoSuchElementException () Constructs a NoSuchElementException with null as

Don't manipulate the NoSuchElementException, wrap it in a custom exception.

try {
    try {
        // We simulate a failing .get() on an Optional.
        throw new NoSuchElementException("message from Optional.get()");
    } catch (NoSuchElementException ex) {
        // We wrap the exception into a custom exception and throw this.
        throw new MyException("my message", ex);
    }
} catch (MyException ex) {
    // Now we catch the custom exception and can inspect it and the
    // exception that caused it.
    System.err.println(ex.getClass().getCanonicalName()
            + ": " + ex.getMessage()
            + ": " + ex.getCause().getMessage());
}

Output:

MyException: my message: message from Optional.get()

Customize HTTP Error Responses in Spring Boot, This is the class ErrorResource that process the requests to the The function getBean(int id) throws an exception of the type NoSuchElementException if it doesn't find the But, as we said, we want the error message is customized. Optional: Create a free Heroku account at https://signup.heroku.com/. public class NoSuchElementException extends RuntimeException Thrown by various accessor methods to indicate that the element being requested does not exist. Since:

ERROR 2448 NoSuchElementException No value present – Yawin , If the hibernate returns an empty optional object, this exception will be thrown. NoSuchElementException: No value present] with root cause java.util. Add proper exception handling code around optional element in rest controller class How to Customize Default Error Message using @ControllerAdvice in Spring… public class NoSuchElementException extends RuntimeException. Thrown by the nextElement method of an Enumeration to indicate that there are no more elements in the enumeration. Enumeration, Enumeration.nextElement (), Serialized Form. Constructor Summary. Constructor and Description. NoSuchElementException ()

Nothing is better than the Optional type, Changing your code to use the Optional class has these effects: When your code throws a NullPointerException or NoSuchElementException , the underlying logic bug is Changing the exception that is thrown doesn't fix the defect or improve the code There is no need to change your code to call methods of Optional . In this article, I will explain how to return custom HTTP errors in Spring Boot. When we make an HTTP request to a resource, it is common that the request has to consider the option of returning

java.util.NoSuchElementException with Dagger 2.27 · Issue #1793 , The error message does not really give any information. NoSuchElementException with Dagger 2.27 #1793 Optional.ifPresent(Optional​.java:159) at We put FragmentBindingsModule::class into the TestAppComponent extra because we Edit: Actually @PerFragment annotation is already added in  , but we are also encouraged by the stories of our readers finding help through our site. During these challenging times, we guarantee we will work tirelessly to support you.

Comments
  • I suggest a read on how to use ORM to delete all that stuff in one go instead of what you do no. That instead of abusing an optional like that.
  • What about Optional#orElseThrow.