跳到主要內容

處理例外狀況與錯誤

為了處理不同類型的錯誤,您可以使用 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
}

請參閱錯誤參考以取得不同錯誤類型及其代碼的詳細分類。