【问题标题】:Error while throwing User defined exception using orElseThrow in java 8 [duplicate]在java 8中使用orElseThrow抛出用户定义的异常时出错[重复]
【发布时间】:2019-05-23 02:39:08
【问题描述】:

我正在尝试使用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; 
}

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

@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) Optional 不适用于参数 (UserNotFoundException)

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

提前致谢。

【问题讨论】:

    标签: java java-8 optional throw


    【解决方案1】:

    应该是供应商:

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

    【讨论】:

      猜你喜欢
      • 2020-10-28
      • 1970-01-01
      • 2021-10-16
      • 2013-11-17
      • 1970-01-01
      • 2015-04-25
      • 2014-06-26
      • 1970-01-01
      • 2012-06-03
      相关资源
      最近更新 更多