Search code examples
javaspringspring-bootexceptionoption-type

Execute multiple lines in orElseThrow


I have the following code block that throws exception if the user is not found. On the other hand, in addition to throwing exception, I also want to call a method when user is not found. So, can I call it by adding another .orElseThrow etc. or shall I convert this block in a standard if condition?

final User user = userRepository.findByUsername(request.getUsername())
                .orElseThrow(InvalidCredentialsException::new);

Solution

  • Just do like it:

    final User user = userRepository.findByUsername(request.getUsername())
                    .orElseThrow(() -> {
                                    System.out.println("multiple lines");
                                    return new InvalidCredentialsException();
                                    });