处理异常和错误
为了处理不同类型的错误,您可以使用 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: '[email protected]' } })
} 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
}
有关不同错误类型及其代码的详细分类,请参阅错误参考。