抛出状态异常

时间:2017-09-27 01:34:15

标签: java spring spring-mvc spring-boot

我有一个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')

并且无法使用ResponseEntityHttpStatus等对象。

我想在https://github.com/JonkiPro/REST-Web-Services/blob/master/src/main/java/com/service/app/rest/controller/advice/ErrorFieldsExceptionHandler.java处获得结果,但没有org.springframework.web

我可以被告知如何将状态和错误列表对象作为响应抛出异常?

1 个答案:

答案 0 :(得分:0)

让我们锻炼好老Single Responsibility Principle

服务层不关心HTTP状态。从 Service 层投掷某种HttpStatus404Exception不是一个好选择。如果有人想在直接连接到数据库的批处理器中使用 Service 层,怎么样?在这种情况下,HttpStatus404Exception完全不合适。

抛出UserNotFoundException(可以扩展NotFoundException)并让 Controller 图层(在您的情况下为 WebController 图层)处理优雅的例外。