javascriptnode.jstry-catchprisma

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


I have this piece of code (the error handler is taken from the 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'
        )
      }
    }
  }

The try/catch block should in theory prevent the application from crashing when a unique constraint is violated, but when I try to trigger the error the application just crash:

  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' }
}

it seems to completely ignore the try/catch block, how can I solve this?


Solution

  • try/catch only works with synchronous code, or with asynchronous code that is using await, you forgot to use await there:

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

    If you prefer to use promises you can use promise catch method instead of 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'
            )
          }
        }
    })