Spring事务抛出Exception异常不回滚

今天有个业务逻辑流程为:

1.访客预约确认先更新预约状态为“预约确认”

2.调用http接口发短信、更新预约状态为“预约成功”等一系列操作

这里面有个问题,如果第2步调接口异常或返回失败。则第1步需要回滚。开始我的代码如下:

	public void updateStatusConfirm(int id) throws Exception {
		appointmentMapper.updateStatusConfirm(id);
		String res = Httper.get(appConfirmUrlPre + URL_SUFFIX + id);
		log.info("预约确认接口返回值为:" + res);
		if (StringUtils.isBlank(res) || !"0".equals(JSON.parseObject(res).getString("resultCode"))) {
			throw new Exception("预约确认接口返回失败,请稍后重试!");
		}
	}

结果发现第1步执行成功,而第2步返回失败,事务并没有回滚。

后来才发现,捕获了异常不会发生事务回滚,除非抛出RuntimeException异常,更改代码如下:

	public void updateStatusConfirm(int id) throws Exception {
		appointmentMapper.updateStatusConfirm(id);
		String res = Httper.get(appConfirmUrlPre + URL_SUFFIX + id);
		log.info("预约确认接口返回值为:" + res);
		if (StringUtils.isBlank(res) || !"0".equals(JSON.parseObject(res).getString("resultCode"))) {
			throw new RuntimeException("预约确认接口返回失败,请稍后重试!");
		}
	}

就可以了。

这也意味着在service层最好不要捕获异常,否则不会回滚。

猜你喜欢

转载自blog.csdn.net/qingmengwuhen1/article/details/80969781