大佬教程收集整理的这篇文章主要介绍了@ControllerAdvice 异常处理程序的 Spring 激活,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
我用@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 (将#修改为@)
以上是大佬教程为你收集整理的@ControllerAdvice 异常处理程序的 Spring 激活全部内容,希望文章能够帮你解决@ControllerAdvice 异常处理程序的 Spring 激活所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。