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

例外とエラーの処理

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

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

© . All rights reserved.