You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Prisma事务中错误未捕获问题求助

问题分析与修复方案

核心问题

你在事务中使用forEach(async (color) => { ... })的方式存在错误:forEach不会等待内部的异步操作完成,导致事务还没执行完所有颜色插入逻辑,就提前返回了success: true;同时,异步操作中的错误无法被外层try/catch捕获,自然不会触发事务回滚和错误响应。

修复步骤

1. 替换forEach为Promise.all

将遍历颜色的逻辑改为map+Promise.all,确保所有颜色插入操作都完成后再结束事务:

const prisma = new PrismaClient();
const STORE_PRODUCT = async (req, res) => {
  try {
    await prisma.$transaction(async (tx) => {
      const { name, description, price, colors } = req.body;

      const product = await tx.products.create({
        data: {
          name,
          description,
          business_id: 2,
          created_by: 1,
        },
      });

      // 用map+Promise.all替代forEach,等待所有异步插入操作完成
      await Promise.all(colors.map(async (color) => {
        await tx.product_Color.create({
          data: {
            name: color,
            product_id: product.id,
          },
        });
      }));
    });

    // 事务执行成功后再返回响应
    return res.status(200).json({
      success: true,
    });
  } catch (error) {
    console.log(error);
    return res.status(500).json({
      success: false,
      message: error.message,
    });
  }
};

2. 检查参数与Schema匹配

  • 确认colors数组中的每个color值不为空,避免name: color传入空值导致参数缺失错误;
  • 核对schema.prisma中product_Color表的字段定义,确保name和product_id都是必填字段,且字段名与代码中的一致(比如是否是productId而不是product_id,取决于你的Schema配置)。

关键说明

Prisma的交互式事务会等待内部所有异步操作完成后才提交,使用Promise.all能确保所有颜色插入操作都被事务监控,一旦其中任何一个出错,整个事务会回滚,并且错误会被外层try/catch捕获,返回错误响应。

内容的提问来源于stack exchange,提问作者Illyrian

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 07:25:17