使用带回调的棱镜查询似乎忽略了 try/catch 块(节点)

Using a prisma query with callback seems to ignore try/catch blocks (Node)

我有这段代码(错误处理程序取自prisma docs):

try {
    prisma.daRevisionare.create({ data: { "idTweet": tweet.id, "testo": testotweet, url } }).then((dati) => {
      bot.sendMessage(chatId, testotweet, { "reply_markup": { "inline_keyboard": [[{ "text": "Aggiungi", "callback_data": `si,${dati.id}` }], [{ "text": "Scarta", "callback_data": `no,${dati.id}` }]] } })
    })
  } catch (e) {
    if (e instanceof Prisma.PrismaClientKnownRequestError) {
      if (e.code === 'P2002') {
        console.log(
          'There is a unique constraint violation, a new user cannot be created with this email'
        )
      }
    }
  }

理论上,try/catch 块应该可以防止应用程序在违反唯一约束时崩溃,但是当我尝试触发错误时,应用程序只会崩溃:

  45 try {
→ 46   prisma.daRevisionare.create(
  Unique constraint failed on the constraint: `daRevisionare_idTweet_key`
    at cb (/Users/lorenzo/Desktop/anti-nft/Gen/bot_telegram/node_modules/@prisma/client/runtime/index.js:38703:17)
    at async PrismaClient._request (/Users/lorenzo/Desktop/anti-nft/Gen/bot_telegram/node_modules/@prisma/client/runtime/index.js:40853:18) {
  code: 'P2002',
  clientVersion: '3.9.1',
  meta: { target: 'daRevisionare_idTweet_key' }
}

似乎完全忽略了try/catch块,我该如何解决?

try/catch 仅适用于同步代码,或使用 await 的异步代码,您忘记在那里使用 await

try {
    await prisma.daRevisionare.create(...)
}

如果你更喜欢使用 promise,你可以使用 promise catch 方法而不是 try/catch:

prisma.daRevisionare.create(...).then(...).catch(e => {
    if (e instanceof Prisma.PrismaClientKnownRequestError) {
      if (e.code === 'P2002') {
        console.log(
          'There is a unique constraint violation, a new user cannot be created with this email'
        )
      }
    }
})