【问题标题】:Spring MVC: Optional vs Exceptions in Service LayerSpring MVC:服务层中的可选与异常
【发布时间】:2017-10-05 09:50:36
【问题描述】:

我想构建一个服务层来处理用户。

您对处理无效 ID 有什么建议。返回 Optional 还是抛出异常?服务层由返回 html 视图的表示层调用。

也许还涉及处理表示层中的错误? (默认错误页面、日志记录...)

可选

public Optional<User> findOne( Long id ) {

        try {
            User user = userRepository.findOne( id );

            return Optional.ofNullable( user );

        // something blow up in the Repository Layer
        } catch ( Exception ex ) {
            throw new ServiceException( ex );
        }
    }

例外

public User findOne( Long id ) {

        try {
            User user = userRepository.findOne( id );

        // something blow up in the Repository Layer
        } catch ( Exception ex ) {
            throw new ServiceException( ex );
        }

        if ( user == null )
            throw new ServiceException( "Invalid Id" );

        return user;
    }

【问题讨论】:

    标签: spring spring-mvc exception optional service-layer


    【解决方案1】:

    我想这更像是一个哲学问题而不是编程问题。

    例如,您的系统中有用户登录。

    当您尝试获取用户详细信息 userService.getDetails(userId) 时,您应该抛出异常(因为如果没有关于他的额外数据,您就无法登录 used)——这是错误。

    但是,如果您尝试获取他的朋友userService.getFriends(userId),则如果没有任何具有给定 id 的记录就可以了。所以 Optional 在这种情况下是很好的回应。

    我是这样想的。

    【讨论】:

      猜你喜欢
      • 2016-03-09
      • 2015-11-03
      • 2016-03-03
      • 2015-06-06
      • 2023-04-09
      • 1970-01-01
      • 2011-10-29
      • 2016-01-27
      • 2018-07-18
      相关资源
      最近更新 更多