2017-09-27 224 views
2

我有一個core模塊,其具有這樣的關係投擲狀態異常

compile('org.springframework.boot:spring-boot-starter-data-jpa') 
compile('org.springframework.boot:spring-boot-starter-mail') 

在方法服務我想拋出異常(或以其他方式)從狀態代碼(例如,404未找到)如果用戶沒有找到。

getById(Long id) { 
    //if the user with specified id does not exist 

    //for example, cast an exception throw new UserNotFoundException(new List<FieldError>); with a list of error fields 
    } 

的問題是,這種模塊具有不依賴

compile('org.springframework.boot:spring-boot-starter-web') 

和不能使用的對象,例如ResponseEntityHttpStatus

我想達到這樣的結果,如https://github.com/JonkiPro/REST-Web-Services/blob/master/src/main/java/com/service/app/rest/controller/advice/ErrorFieldsExceptionHandler.java,但沒有org.springframework.web

我可以建議我如何拋出異常與狀態和錯誤列表對象作爲響應?

+0

狀態'404 NOT FOUND'基本上是一個HTTP狀態碼,如果你想要這樣但沒有'org.springframework.web'的東西,那麼你用什麼樣的框架來處理這個servlet呢? –

回答

0

讓我們鍛鍊好舊的Single Responsibility Principle

服務層不關心HTTP狀態。從服務層投擲某種HttpStatus404Exception是不是一個好的選擇。怎麼樣,如果有人想在直接連接到數據庫的批處理器使用服務層?在這種情況下,HttpStatus404Exception完全不合適。

拋出一個UserNotFoundException(可擴展NotFoundException),並讓控制器層(在你的情況下,WebController層)妥善地處理異常。