spring boot 全局异常处理可以通过配置 @controlleradvice 结合 @exceptionhandler 来捕获锁超时异常。具体做法是识别抛出该异常的类(如 pessimisticlockingfailureexception 或 timeoutexception),在 advice 中统一返回 json 响应,并在业务层通过重试机制或事务回滚来处理。

如何区分不同类型的锁超时异常
在 Spring Boot 中,锁超时异常主要来源于数据库层面和分布式锁层面。数据库悲观锁通常抛出 PessimisticLockingFailureException,而 Redisson 等分布式锁可能抛出 RedisConnectionException 或直接由框架包装的 LockTimeoutException。需要针对不同的来源编写对应的 @ExceptionHandler 方法。

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class LockApplication {
public static void main(String[] args) {
SpringApplication.run(LockApplication.class, args);
}
}
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.orm.jpa.JpaSystemException;
import org.hibernate.exception.LockTimeoutException;
import org.springframework.http.ResponseEntity;
import java.util.HashMap;
import java.util.Map;
@RestControllerAdvice
public class GlobalLockExceptionHandler {
@ExceptionHandler(LockTimeoutException.class)
public ResponseEntity<Map<String, Object>> handleLockTimeout(LockTimeoutException ex) {
Map<String, Object> body = new HashMap<>();
body.put("error", "LOCK_TIMEOUT");
body.put("message", "资源正被占用,请稍后重试");
return ResponseEntity.status(409).body(body);
}
@ExceptionHandler(Exception.class)
public ResponseEntity<Map<String, Object>> handleGeneral(Exception ex) {
Map<String, Object> body = new HashMap<>();
body.put("error", "INTERNAL_ERROR");
body.put("message", "系统内部错误");
return ResponseEntity.status(500).body(body);
}
}基于事务回滚的具体问题
当捕获到锁超时异常时,必须确保当前事务正确回滚,否则可能导致数据不一致。在 @Transactional 方法中,如果未显式声明 rollbackFor,Spring 默认只对 RuntimeException 和 Error 进行回滚。由于某些锁超时异常可能是 Exception 的子类而非运行时异常,因此需要在注解中明确指定回滚类型,或者在 @ExceptionHandler 中手动触发回滚逻辑。


















