[英]Prisma failed queries don't return proper errors
在我的 Prisma/express 后端,我有这个模式:
架构. schema.prisma
:
model user {
id Int @id @default(autoincrement())
name String
last_name String
role role @relation(fields: [role_id], references: [id])
role_id Int
birth_date DateTime
created_at DateTime @default(now())
updated_at DateTime @updatedAt
}
model role {
id Int @id @default(autoincrement())
description String
user user[]
}
当我尝试插入无效的数据(例如错误的数据类型)时,我在控制台上得到了完整的错误,但我永远无法在代码上检索它,以便我可以根据 Prisma 的错误代码处理错误在其文档上。 每当我记录或返回我的请求响应时,这就是我得到的:
{ "clientVersion": "3.8.1" }
这是我执行查询的地方,我希望根据文档得到正确的错误:
user.controller.ts
:
import { PrismaClient } from "@prisma/client";
import { Request, Response } from "express";
const mockData = {
name: "test",
last_name: "test_lastname",
birth_date: "28/07/1999", // invalid Date
role_id: "1" // invalid type, should be Int
}
module.exports = {
post: async function (req: Request, res: Response) {
const prisma: any = new PrismaClient();
try {
const result = await prisma.user.create({
data: mockData,
});
res.json(result);
} catch (err) {
return res.json(err);
}
},
};
我认为您可能需要阅读有关正确错误处理的这部分文档: https://www.prisma.io/docs/concepts/components/prisma-client/handling-exceptions-and-errors
只是引用它,您需要使用instanceof
调用检查错误以确定它是什么类型的错误,它具有什么属性,并相应地处理它。
例如PrismaClientKnownRequestError
有code
属性,但PrismaClientValidationError
没有等等。
例子:
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
}
关于你的代码,我们真的不知道res.json(err);
在幕后,很难说为什么它只返回clientVersion
,但只有console.log
应该在错误 object 上调用.toString()
方法,你应该得到更多关于它的信息,而不仅仅是clientVersion
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.