我有這段代碼(錯誤處理程式取自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 塊,我該如何解決這個問題?
uj5u.com熱心網友回復:
try/catch僅適用于同步代碼或正在使用的異步代碼await,您忘記在await那里使用:
try {
await prisma.daRevisionare.create(...)
}
如果你更喜歡使用 Promise,你可以使用 Promisecatch方法而不是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'
)
}
}
})
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/426134.html
標籤:javascript 节点.js 试着抓 棱镜
