简体   繁体   English

如何在连接到 Mongo 存储库的 Java/Spring 控制器上抛出异常?

[英]How to throw exceptions on Java/Spring controller connected to Mongo repository?

I am getting more familiar with Spring Boot and to do so, I am building a REST api which is connected to a mongo db, therefore I am using a Mongo Repository.我越来越熟悉 Spring Boot,为此,我正在构建一个连接到 mongo db 的 REST api,因此我使用的是 Mongo 存储库。 I have this endpoint on my controller which is responsible for deleting a resource (expert in this case) from my database:我的控制器上有这个端点,它负责从我的数据库中删除资源(在这种情况下是专家):

@RestController
@RequestMapping("/experts")
class ExpertController {
    @Autowired
    private  ExpertRepository repository;

    @RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
    public void deleteExpert(@PathVariable ObjectId id) {
        repository.delete(repository.findBy_id(id));
    }

} }

My question is how could I throw an exception in case the id of the resource which is added does not exist on the database?我的问题是,如果数据库中不存在添加的资源的id ,我怎么能抛出异常? Thanks in advance !提前致谢 !

You can simply use throw new MyCustomIdNotFoundException();您可以简单地使用throw new MyCustomIdNotFoundException();

Just make sure you mark your controller method as throwing that exception.只需确保将控制器方法标记为抛出该异常即可。

You can then handle that exception using Spring's exception handling tools, a good article on which is available at: https://www.baeldung.com/exception-handling-for-rest-with-spring然后,您可以使用 Spring 的异常处理工具来处理该异常,该文章可在以下网址获得: https : //www.baeldung.com/exception-handling-for-rest-with-spring

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

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