在Java 8

时间:2018-12-23 15:30:05

标签: java java-8 optional throw

我正在尝试使用orElseThrow java 8命令抛出一个自定义的专有名词。但是我收到以下编译错误:

public class UserInvitationServiceImpl implements UserInvitationService{

    @Autowired
    private UserRepository userRepository;

    @Override
    public void inviteUser(String email) throws UserNotFoundException {
        // TODO Auto-generated method stub
        if(email!= null && !email.isEmpty()) {
            Optional<User> optionalUser = userRepository.findByEmail(email);
            optionalUser.orElseThrow(new UserNotFoundException("User doesnt exist in system"));
        }
    }       
}

public interface UserInvitationService {   
    void inviteUser(String email) throws UserNotFoundException; 
}

我的自定义异常类UserNotFoundException扩展了RunTimeException,如下所示:

@ResponseStatus(value = HttpStatus.NOT_FOUND)
public class UserNotFoundException extends RuntimeException {

    /**
     * 
     */
    private static final long serialVersionUID = 9093519063576333483L;

    public UserNotFoundException( String message) {
        super(message);
    }    
}

我在orElseThrow语句中收到此错误:

  

类型中的方法orElseThrow(Supplier)   可选不适用于参数   (UserNotFoundException)

这是什么问题,以及如何通过orElseThrow引发自定义用户定义的异常?

谢谢。

1 个答案:

答案 0 :(得分:3)

它应该是供应商:

.orElseThrow(() -> new UserNotFoundException("User doesnt exist in system"));