我对Spring Boot越来越熟悉,为此,我正在构建一个连接到mongo数据库的REST api,因此我正在使用Mongo存储库。我在控制器上有此端点,该端点负责从数据库中删除资源(在这种情况下为专家):
@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));
}
} }
我的问题是,如果数据库中不存在所添加资源的id
,该如何引发异常?预先感谢!
您可以简单地使用throw new MyCustomIdNotFoundException();
只需确保您将控制器方法标记为引发该异常。
然后,您可以使用Spring的异常处理工具来处理该异常,有关该异常的文章,请访问https://www.baeldung.com/exception-handling-for-rest-with-spring