【问题标题】:Which practice is better when throwing an exception in a service?在服务中引发异常时,哪种做法更好?
【发布时间】:2020-06-19 14:36:06
【问题描述】:

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

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

【问题讨论】:

  • 您在第一个 sn-p 中查询了存储库两次。这使得两者中的情况更糟。对于返回 404 Not found 的两个 sn-ps 也是不错的设计

标签: java spring api rest


【解决方案1】:

使用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));
    }
}

【讨论】:

    猜你喜欢
    • 2013-03-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-12
    • 2017-06-08
    • 1970-01-01
    • 2012-04-29
    • 1970-01-01
    相关资源
    最近更新 更多