在Java 8中使用orElseThrow引发用户定义的异常时出错 [英] Error while throwing User defined exception using orElseThrow in java 8

查看:571
本文介绍了在Java 8中使用orElseThrow引发用户定义的异常时出错的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to throw an custom excpetion using orElseThrow java 8 command. However I am getting the following compile errors:

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,如下所示:

And my custom exception class, UserNotFoundException which extends RunTimeException is as follows:

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

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

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

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

I am getting this error at orElseThrow statement:

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

The method orElseThrow(Supplier) in the type Optional is not applicable for the arguments (UserNotFoundException)

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

What is the issue here and how to throw custom user defined exception via orElseThrow?

谢谢.

推荐答案

它应该是供应商:

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

这篇关于在Java 8中使用orElseThrow引发用户定义的异常时出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆