2017-09-27 178 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层)妥善地处理异常。