【发布时间】: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