fix(coupon): 优化事务回滚标记逻辑

- 添加对无事务上下文情况的处理
- 避免在非事务环境下抛出异常
- 提高优惠券领取失败时的系统稳定性
This commit is contained in:
2025-11-17 08:52:00 +08:00
parent 7c906d5529
commit 8efd16ba56

View File

@@ -17,6 +17,7 @@ import lombok.RequiredArgsConstructor;
import java.util.Date;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.NoTransactionException;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
@@ -292,7 +293,7 @@ public class CouponServiceImpl implements ICouponService {
return CouponClaimResult.success(claimRecord, coupon);
} catch (CouponInvalidException e) {
TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
markRollbackOnly();
log.warn("领取优惠券失败(业务校验不通过): userId={}, couponId={}, reason={}",
request.getUserId(), request.getCouponId(), e.getMessage());
String errorCode = e.getErrorCode() == null
@@ -300,10 +301,18 @@ public class CouponServiceImpl implements ICouponService {
: e.getErrorCode();
return CouponClaimResult.failure(errorCode, e.getMessage());
} catch (Exception e) {
TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
markRollbackOnly();
log.error("领取优惠券失败: userId={}, couponId={}",
request.getUserId(), request.getCouponId(), e);
return CouponClaimResult.failure(CouponClaimResult.ERROR_SYSTEM_ERROR, "系统错误,领取失败:" + e.getMessage());
}
}
private void markRollbackOnly() {
try {
TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
} catch (NoTransactionException ex) {
log.debug("未检测到Spring事务上下文,跳过回滚标记");
}
}
}