在java自定义异常中结合事务回滚,核心做法是让spring的事务管理器识别特定的异常类型并触发回滚。默认情况下,spring仅对运行时异常(runtimeexception)和error进行回滚,而检查型异常(checked exception)不会触发回滚。因此,你需要在自定义异常类上添加 @transactional(rollbackfor = yourcustomexception.class) 注解,或者在方法签名中抛出该异常并在调用处捕获处理,同时在service层确保事务边界正确包裹了业务逻辑。

如何配置自定义异常触发回滚
要让自定义异常触发回滚,最直接的方式是在Service方法或类上使用 @Transactional 注解,并通过 rollbackFor 属性指定你的自定义异常类。这样,当方法抛出该异常时,Spring的事务代理会捕获它并执行回滚操作,而不是像处理普通检查型异常那样忽略它。这种方法适用于大多数基于Spring Boot的项目,无需修改全局配置。

import org.springframework.transaction.annotation.Transactional;
public class BusinessException extends Exception {
public BusinessException(String message) {
super(message);
}
}
@Service
public class OrderService {
@Transactional(rollbackFor = BusinessException.class)
public void createOrder(OrderDTO dto) throws BusinessException {
// 模拟业务逻辑
if (dto.getAmount() <p>上述代码中,<code>createOrder</code> 方法被 <code>@Transactional</code> 包裹,并明确指定了 <code>rollbackFor = BusinessException.class</code>。当 <code>amount</code> 小于等于0时,抛出 <code>BusinessException</code>,事务会自动回滚。如果不指定 <code>rollbackFor</code>,由于 <code>BusinessException</code> 继承自 <code>Exception</code>(检查型异常),事务将不会回滚,导致数据不一致。</p><h2>全局异常处理与事务回滚的配合</h2><p>在实际项目中,通常会在Controller层使用 <code>@RestControllerAdvice</code> 统一处理异常,但这不影响Service层的事务回滚。关键在于Service层的方法必须正确声明事务和回滚条件。如果Service层没有正确配置 <code>rollbackFor</code>,即使Controller层捕获了异常,事务也不会回滚。此外,如果在Service内部捕获了异常而没有重新抛出,事务也会正常提交。因此,确保异常向上抛出是事务回滚生效的前提。</p><div class="aritcle_card flexRow artxards">
<div class="artcardd flexRow">
<a class="aritcle_card_img" rel="nofollow" href="/xiazai/skill11083" title="Java调试"><img
src="https://img.php.cn/upload/skill/001/246/273/6adaf20dbae7c507.jpg" alt="Java调试" onerror="this.onerror='';this.src='/static/lhimages/moren/morentu.png'" ></a>
<div class="aritcle_card_info flexColumn">
<a rel="nofollow" href="/xiazai/skill11083" title="Java调试" class="overflowclass">Java调试</a>
<p class="overflowclass">通过 JDWP 实现 Java 远程调试:连接远程 JVM、设置断点、单步执行代码、查看变量值、获取调用栈。适用于需要调试远程 Java 应用、排查运行时状态、追踪代码执行流程的场景。
术语注解
JDWP:Java Debug Wire Protocol,Java 调试有线协议(Java 远程调试底层通信协议)
remote JVM:远程 Java 虚拟机
step through code:代码单步调试(步入 / 步过 / 步出调试)
inspect variables:变量查看 / 变量检视
stac</p>
</div>
<a rel="nofollow" href="/xiazai/skill11083" title="Java调试" class="aritcle_card_btn flexRow flexcenter"><b></b><span>下载</span>
</a>
</div>
</div><p><img src="https://img.php.cn/upload/article/001/242/473/179437856152343.png?x-oss-process=image/resize,p_40" alt="Java 自定义异常中事务回滚怎么和异常结合"></p><pre class="brush:php;toolbar:false;">import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(BusinessException.class)
public ResponseEntity<string> handleBusinessException(BusinessException e) {
return ResponseEntity.status(400).body(e.getMessage());
}
@ExceptionHandler(Exception.class)
public ResponseEntity<string> handleException(Exception e) {
return ResponseEntity.status(500).body("系统内部错误");
}
}</string></string>
在全局异常处理器中,我们捕获 BusinessException 并返回400状态码。这不会影响Service层已经发生的事务回滚。如果Service层抛出了未处理的 RuntimeException,Spring也会自动回滚。但如果是检查型异常且未配置 rollbackFor,则不会回滚。因此,务必在Service层显式配置回滚规则。
自定义异常中携带错误码的具体问题
在自定义异常中携带错误码,可以方便前端或日志系统快速定位问题。例如,在 BusinessException 中添加一个 errorCode 字段,并在抛出时传入具体的错误码。这样,全局异常处理器可以根据错误码返回更精确的错误信息。同时,事务回滚机制不受影响,因为回滚只关注异常类型,不关注异常内容。
public class BusinessException extends Exception {
private final String errorCode;
public BusinessException(String errorCode, String message) {
super(message);
this.errorCode = errorCode;
}
public String getErrorCode() {
return errorCode;
}
}
// 使用示例
throw new BusinessException("E001", "用户不存在");
通过这种方式,你可以在保持事务回滚功能的同时,增强异常的语义化表达能力。错误码可以作为常量定义在枚举中,便于维护和管理。
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南










