我有一个core
模块,它有这样的关系
compile('org.springframework.boot:spring-boot-starter-data-jpa')
compile('org.springframework.boot:spring-boot-starter-mail')
在方法服务中我想在状态代码中抛出异常(或其他)(例如,NOT FOUND 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')
并且无法使用ResponseEntity
或HttpStatus
等对象。
我想在https://github.com/JonkiPro/REST-Web-Services/blob/master/src/main/java/com/service/app/rest/controller/advice/ErrorFieldsExceptionHandler.java处获得结果,但没有org.springframework.web
。
我可以被告知如何将状态和错误列表对象作为响应抛出异常?
答案 0 :(得分:0)
让我们锻炼好老Single Responsibility Principle。
服务层不关心HTTP状态。从 Service 层投掷某种HttpStatus404Exception
不是一个好选择。如果有人想在直接连接到数据库的批处理器中使用 Service 层,怎么样?在这种情况下,HttpStatus404Exception
完全不合适。
抛出UserNotFoundException
(可以扩展NotFoundException
)并让 Controller 图层(在您的情况下为 WebController 图层)处理优雅的例外。