2017-05-07 111 views
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; 
    } 

回答

1

我想這更多的是一種比編程思想的問題。

例如,您有用戶登錄您的系統。

當您嘗試獲取用戶詳細信息userService.getDetails(userId)時,應該拋出異常(因爲無法在沒有關於他的額外數據的情況下使用記錄) - 這是錯誤。

但是,如果你試圖讓他的朋友userService.getFriends(userId),沒有給定的ID沒有任何記錄是可以的。所以在這種情況下,可選是很好的迴應。

我想這樣。

+0

有趣的點! – Dachstein