處理異常和錯誤
為了處理不同型別的錯誤,您可以使用 instanceof 來檢查錯誤型別並相應地進行處理。
以下示例嘗試建立一個電子郵件記錄已存在的使用者。這將丟擲錯誤,因為 email 欄位已應用了 @unique 屬性。
schema.prisma
model User {
id Int @id @default(autoincrement())
email String @unique
name String?
}
使用 Prisma 名稱空間訪問錯誤型別。然後可以檢查錯誤程式碼並列印訊息。
import { PrismaClient, Prisma } from '@prisma/client'
const client = new PrismaClient()
try {
await client.user.create({ data: { email: 'alreadyexisting@mail.com' } })
} catch (e) {
if (e instanceof Prisma.PrismaClientKnownRequestError) {
// The .code property can be accessed in a type-safe manner
if (e.code === 'P2002') {
console.log(
'There is a unique constraint violation, a new user cannot be created with this email'
)
}
}
throw e
}
有關不同錯誤型別及其程式碼的詳細分類,請參閱錯誤參考。