1

What I want to do is, updating a customer if it is present but if there is no customer then throw an exception. But I could not find the correct stream function to do that. How can I achieve this ?

public Customer update(Customer customer) throws Exception {
        Optional<Customer> customerToUpdate = customerRepository.findById(customer.getId());
        customerToUpdate.ifPresentOrElse(value -> return customerRepository.save(customer),
        throw new Exception("customer not found"));
    }

I could not return the value coming from save function because it is saying that it is void method and not expecting return value.

Alexander Ivanchenko
  • 25,667
  • 5
  • 22
  • 46
Chris Garsonn
  • 717
  • 2
  • 18
  • 32
  • 5
    Don't store the optional, immediately use `orElseThrow();` after findById and store the nonnull result. – Guillaume F. Apr 13 '22 at 07:03
  • You can also take a look here: https://stackoverflow.com/questions/41485751/java-8-optional-ifpresent-return-object-orelsethrow-exception – happy songs Apr 13 '22 at 07:05
  • I would put exceptions first, then the "actual code". So, probably `customer = customerRepository.findById(...).orElseThrow(() -> new NotFoundException(...))` and then `/* some more code */; return customerRepository.save(customer);` would be more readable and maintainable. – terrorrussia-keeps-killing Apr 13 '22 at 07:05
  • https://stackoverflow.com/questions/42993428/throw-exception-in-optional-in-java8 –  Apr 13 '22 at 07:10

1 Answers1

6

As Guillaume F. already said in the comments, you could just use orElseThrow here:

Customer customer = customerRepository.findById(customer.getId())
    .orElseThrow(() -> new Exception("customer not found"));
return customerRepository.save(customer);

By the way, avoid throwing Exception, as that exception is too broad. Use a more specific type, like NotFoundException.

MC Emperor
  • 22,334
  • 15
  • 80
  • 130
  • 1
    Thanks buddy. Yes as you said, I will not throw exception just wrote it for the question, I am defining custom exceptions with controller advice and global exception handlers etc. – Chris Garsonn Apr 13 '22 at 07:51
  • But this code snippet is also giving error and maybe not correct as syntax – Chris Garsonn Apr 13 '22 at 07:55
  • 1
    Well, you need to remove the `throw` keyword. `orElseThrow` requires one to *supply* the exception, and not *throw* it. (Of course, the exception is eventually thrown by the `orElseThrow` method.) – MC Emperor Apr 13 '22 at 09:07