spring|spring JTA 关于异常处理的时机问题

题外话:spring事务管理是通过aop完成的(aop呢也正好是用来干这些事的)
直入正题

@Transcational fun demo(): Response { try { return repository.save(mockedPo) } catch (error: DataIntegrityViolationException) { throw DuplicatedPo() //一个想要抛出的自定义业务异常 } }

此时方法整个交由spring事务管理,在方法执行完毕之后再进行commit或者rollback,catch的时机太早了,还没有flush也就没办法触发DataIntegrityViolationException
所以我们无法在方法内catch住DataIntegrityViolationException继而无法抛出想要
自定义业务异常
如果强行想要在此处catch住,可以在save之后flush一下(并不会这么做)
【spring|spring JTA 关于异常处理的时机问题】解决方法:
try catch放到controller层

    推荐阅读