简体   繁体   English

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

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

I'm working on a Spring Boot CRUD RESTful API and i'm trying to define the best way of doing certain things, for instance:我正在研究 Spring Boot CRUD RESTful API 并且我正在尝试定义做某些事情的最佳方式,例如:

This is my List user by its id endpoint service:这是我的 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);
        }
    }
}

And this is another way of writing it:这是另一种写法:

@Service
public class DetailUserService {

    @Autowired
    UserRepository repository;

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

Both ways work but how do i know which is better?两种方式都有效,但我怎么知道哪个更好?

Using java-8 is always a better choice for less code and more readable code.使用java-8对于更少的代码和更易读的代码来说总是一个更好的选择。
You can use below tyle of as you mentioned it as your second option.您可以使用您提到的以下类型作为您的第二个选项。 Using the Optional.orElseThrow() method represents another elegant alternative to the isPresent()-get() pair使用Optional.orElseThrow()方法代表了isPresent()-get()对的另一种优雅替代方案

You can find out more here https://dzone.com/articles/using-optional-correctly-is-not-optional您可以在这里找到更多信息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