Spring MVC:服务层中的可选与异常
Spring MVC: Optional vs Exceptions in Service Layer
我想构建一个处理用户的服务层。
您对处理无效 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;
}
我想这更像是哲学问题而不是编程问题。
例如,您有用户登录您的系统。
当您尝试获取用户详细信息时 userService.getDetails(userId)
,您应该抛出异常(因为如果没有关于他的额外数据,您就无法记录 used)——这是错误。
但是,如果您尝试获取他的朋友 userService.getFriends(userId)
,即使没有任何具有给定 ID 的记录也没关系。所以 Optional 在这种情况下是很好的回应。
我是这么想的
我想构建一个处理用户的服务层。
您对处理无效 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;
}
我想这更像是哲学问题而不是编程问题。
例如,您有用户登录您的系统。
当您尝试获取用户详细信息时 userService.getDetails(userId)
,您应该抛出异常(因为如果没有关于他的额外数据,您就无法记录 used)——这是错误。
但是,如果您尝试获取他的朋友 userService.getFriends(userId)
,即使没有任何具有给定 ID 的记录也没关系。所以 Optional 在这种情况下是很好的回应。
我是这么想的