0
我想構建一個處理用戶的服務層。Spring MVC:可選vs服務層的例外
您對處理無效ID有何建議?用可選返回或拋出異常?服務層由表示層返回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;
}
有趣的點! – Dachstein