spring-boot - 防止 Spring JPA 将异常包装到 JpaObjectRetrievalFailureException
问题描述
我正在尝试使用自定义存储库,该存储库允许在找不到实体时抛出明确措辞的异常。它看起来像这样:
public interface ItemRepository extends JpaRepository<Item, String>, ItemRepositoryCustom {
Optional<Item> findByItemNumber(String itemNumber);
}
public interface ItemRepositoryCustom {
Item findByItemNumberOrThrow(String itemNumber);
}
public class ItemRepositoryCustomImpl implements ItemRepositoryCustom {
@Autowired
ItemRepository itemRepository;
@Override
public Item findByItemNumberOrThrow(String itemNumber) {
return itemRepository.findByItemNumber(itemNumber).orElseThrow(() ->
new EntityNotFoundException(String.format("The Item with the number %s was not found", itemNumber)));
}
}
我从How to throw exceptions on search methods in spring data jpa 中得到了这个想法。
这种结构原则上是有效的。但是,Spring JPA 似乎包装了这些异常,并且总是抛出 JpaObjectRetrievalFailureException,原因是我的 EntityNotFoundException。
但我不想那样!我们有专门处理 EntityNotFoundExceptions 的 ControllerAdvice,所以我想保持这种状态。
关于如何阻止 Spring JPA 这样做的任何建议?提前致谢!
解决方案
推荐阅读
- html - 一个 div 中的照片被另一个 div 移动
- typescript - 如何使用键盘输入平滑地更新成帧器运动位置?
- python - 从数据库获取数据后,我无法在 html 中显示 MySql 数据,可以在服务器(CMD)中看到
- flutter - Flutter:如何在 Cupertino 主题中为材质小部件设置主题?
- android - Android:2个具有不同appID的应用程序,使用相同的名称.SO Lib,但同一设备上的lib版本不同
- python - 如何使用一组 {cameras} ✕ {textures}(笛卡尔积)在 c4d 中排队批量渲染?
- angular - 从 AWS API Gateway 下载时,Angular 下载 Excel 已损坏
- r - 在处理更大的栅格时处理临时目录和工作区的最佳方法是什么?
- python - 是否可以使用 python 脚本在 ABAQUS 中将分区特征从一个部分复制到另一个非常相似的部分?如果是这样,怎么做?
- http - 通过 nginx 和 hls 流式传输无法完全正常工作