繁体   English   中英

在服务中引发异常时,哪种做法更好?

[英]Which practice is better when throwing an exception in a service?

我正在研究 Spring Boot CRUD RESTful API 并且我正在尝试定义做某些事情的最佳方式,例如:

这是我的 id 端点服务列表用户

@Service
public class DetailUserService {

    @Autowired
    UserRepository repository;

    public Optional<User> listUser(Long id) {

        Optional<User> user = repository.findById(id);
        if (!user.isPresent()) {
            throw new UserNotFoundException(id);
        } else {
            return repository.findById(id);
        }
    }
}

这是另一种写法:

@Service
public class DetailUserService {

    @Autowired
    UserRepository repository;

    public User listUser(Long id) {
        return repository.findById(id)
                .orElseThrow(() -> new UserNotFoundException(id));
    }
}

两种方式都有效,但我怎么知道哪个更好?

使用java-8对于更少的代码和更易读的代码来说总是一个更好的选择。
您可以使用您提到的以下类型作为您的第二个选项。 使用Optional.orElseThrow()方法代表了isPresent()-get()对的另一种优雅替代方案

您可以在这里找到更多信息https://dzone.com/articles/using-optional-correctly-is-not-optional

@Service
public class DetailUserService {

    @Autowired
    UserRepository repository;

    public User listUser(Long id) {
        return repository.findById(id)
                .orElseThrow(() -> new UserNotFoundException(id));
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM