首页 > 解决方案 > 在服务中引发异常时,哪种做法更好?

问题描述

我正在开发一个 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));
    }
}

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

标签: javaspringapirest

解决方案


对于更少的代码和更易读的代码,使用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));
    }
}

推荐阅读