fix(planting-service): 添加 P2002 错误捕获处理并发创建冲突
PostgreSQL 的 upsert 在高并发下仍可能出现唯一约束错误, 添加 try-catch 捕获 P2002 错误,发生冲突时直接查询返回已存在的记录。 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
This commit is contained in:
parent
68e269b602
commit
e7f2d69def
|
|
@ -43,6 +43,8 @@ export class ContractSigningTaskRepositoryImpl implements IContractSigningTaskRe
|
||||||
} else {
|
} else {
|
||||||
// 创建 - 使用 upsert 处理并发幂等性
|
// 创建 - 使用 upsert 处理并发幂等性
|
||||||
// 如果 orderNo 已存在,则只返回现有记录(不更新)
|
// 如果 orderNo 已存在,则只返回现有记录(不更新)
|
||||||
|
// 额外捕获 P2002 错误以处理极端并发情况
|
||||||
|
try {
|
||||||
const result = await this.prisma.contractSigningTask.upsert({
|
const result = await this.prisma.contractSigningTask.upsert({
|
||||||
where: { orderNo: task.orderNo },
|
where: { orderNo: task.orderNo },
|
||||||
create: {
|
create: {
|
||||||
|
|
@ -68,6 +70,24 @@ export class ContractSigningTaskRepositoryImpl implements IContractSigningTaskRe
|
||||||
update: {},
|
update: {},
|
||||||
});
|
});
|
||||||
return this.mapToDomain(result);
|
return this.mapToDomain(result);
|
||||||
|
} catch (error: unknown) {
|
||||||
|
// 处理并发创建时的唯一约束冲突 (Prisma P2002)
|
||||||
|
if (
|
||||||
|
error &&
|
||||||
|
typeof error === 'object' &&
|
||||||
|
'code' in error &&
|
||||||
|
error.code === 'P2002'
|
||||||
|
) {
|
||||||
|
// 记录已被其他并发请求创建,直接查询返回
|
||||||
|
const existing = await this.prisma.contractSigningTask.findUnique({
|
||||||
|
where: { orderNo: task.orderNo },
|
||||||
|
});
|
||||||
|
if (existing) {
|
||||||
|
return this.mapToDomain(existing);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
Loading…
Reference in New Issue