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

集中式Prisma Client使用时错误无法正常捕获问题求助

问题根源与解决方案

问题原因

你的问题既不是Prisma也不是Fastify的问题,核心是Prisma中间件里的try-catch吞了错误:

  • 使用集中式单例Prisma Client时,加载的prismaMiddleware.js中,$use中间件用try-catch捕获了Prisma操作的错误,但仅做日志打印,没有重新抛出错误。
  • 这导致错误无法传递到controller层的try-catch块,Fastify因未收到未处理错误,默认返回200状态码。
  • 而在controller内新建Prisma Client时,该Client未挂载中间件,错误直接抛入controller的catch块,因此能正常返回500。

修复方案

修改prismaMiddleware.js的catch逻辑,打印错误后重新抛出,让错误继续向上传递:

const prisma = require("../db/db");
const bcrypt = require("bcrypt");

prisma.$use(async (params, next) => {
  try {
    if (
      params.model === "seller" &&
      (params.action === "create" || params.action === "update")
    ) {
      const seller = params.args.data;
      if (seller.password) {
        seller.password = await bcrypt.hash(seller.password, 10);
      }
    }

    const result = await next(params);
    return result;
  } catch (error) {
    console.log(error);
    // 关键:重新抛出错误,让上层try-catch能捕获
    throw error;
  }
})

额外说明

Prisma推荐使用单例Client是正确的实践,可避免创建过多数据库连接。只要保证中间件内的错误能正常向上传递,就能同时兼顾单例模式与错误捕获需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 00:37:33