问题描述
我用@Service 注释的服务类看起来像:
@Service
@Transactional
public class ItemService {
private final ItemRepo itemRepo;
@Autowired
public ItemService(ItemService itemRepo) {
this.itemRepo = itemRepo;
}
public Item findItemByName(String name) {
return itemRepo.findItemByName(name)
.orElseThrow(() -> new ItemNotFoundException(name));
}
每当在数据库中找不到项目时,此方法会抛出 ItemNotFoundException 由我的 ApiExceptionHandler 扩展了 ResponseEntityExceptionHandler,并用@ControllerAdvice 进行了注释。 这正是我期望发生的事情,但我的问题是如何从 ControllerAdvice 注释类“调用”ItemAlreadyExistsException, 我试过类似
public Item addItem(Item item){ // throws an exception if the item's name already exists.
if (itemRepo.findItemByName(item.getName()).isEmpty())
return itemRepo.save(item);
else throw new ItemAlreadyExistsException(item.getName()));
}
但它要求我在方法的签名中添加 throws 异常,然后不调用 @ControllerAdvice。
或者如果有像 itemRepo.verifyItemNotExist(item.getName()).orElseThrow.. 这可能会做我想要的。
我希望我的问题很清楚,并感谢您的帮助。
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)