メインコンテンツへスキップ

例外とエラーの処理

さまざまな種類のエラーを処理するために、エラーの種類を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
}

さまざまなエラータイプとそのコードの詳細な内訳については、エラーリファレンスを参照してください。