Explain Unexpected Empty Optional

class CandyService {

  private SupplyRepository supplyRepository;

  void updateBarcode(String id, String newBarcode) {
    var supply = supplyRepository.findById(id).orElseThrow();
    supply.setBarcode(newBarcode);
    supplyRepository.save(supply);
  }
}

Since Java 10, orElseThrow() without a parameter returns the value of an Optional or throws a NoSuchElementException. Its documentation recommends it over get(), which does the same but whose name hides the fact that it may throw.

But the exception says nothing more than No value present. When it shows up in the logs, you know that some supply wasn't found, but not which one. You have to reproduce the problem to find out.

class CandyService {

  private SupplyRepository supplyRepository;

  void updateBarcode(String id, String newBarcode) {
    var supply = supplyRepository.findById(id)
        .orElseThrow(() -> new NoSuchElementException("Unknown " + id));
    supply.setBarcode(newBarcode);
    supplyRepository.save(supply);
  }
}

The overload of orElseThrow() that takes a supplier, available since Java 8, lets you throw an exception with a meaningful message. Now the message says which ID wasn't found, so the log entry alone tells you what went wrong.

The supplier is only called when the Optional is empty, so building the message costs nothing in the normal case. The same idea works with your own exception types, for example one that your web layer maps to a 404 Not Found.