Skip to main content

处理异常和错误

为了处理不同类型的错误,你可以使用 instanceof 检查错误是什么并进行相应的处理。

¥In order to handle different types of errors you can use instanceof to check what the error is and handle it accordingly.

以下示例尝试使用现有电子邮件记录创建用户。这将引发错误,因为 email 字段应用了 @unique 属性。

¥The following example tries to create a user with an already existing email record. This will throw an error because the email field has the @unique attribute applied to it.

schema.prisma
model User {
id Int @id @default(autoincrement())
email String @unique
name String?
}

使用 Prisma 命名空间来访问错误类型。然后可以检查 错误代码 并打印一条消息。

¥Use the Prisma namespace to access the error type. The error code can then be checked and a message can be printed.

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
}

请参阅 错误参考 了解不同错误类型及其代码的详细分类。

¥See Errors reference for a detailed breakdown of the different error types and their codes.