繁体   English   中英

抛出状态异常

[英]Throwing the status exception

我有一个具有这种关系的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

可以建议我如何将状态和错误列表对象作为响应引发异常?

让我们行使古老的单一责任原则

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

抛出UserNotFoundException (可以扩展NotFoundException ),并让Controller层(在您的情况下为WebController层)优雅地处理异常。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM