Reputation: 423
In my Prisma/express backend, I have this schema:
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[]
}
When I try to insert data that is not valid(wrong type of data for instance), I get the full error on the console but I can never retrieve it on the code so that I can handle the errors according to error codes that Prisma has on its docs. Whenever I log or return on my requests responses, this is what I get:
{ "clientVersion": "3.8.1" }
This is where I execute the query that I expected to get the proper error as per the docs:
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);
}
},
};
Upvotes: 3
Views: 11396
Reputation: 18526
I think you probably need to read this part of the docs about proper error handling: https://www.prisma.io/docs/concepts/components/prisma-client/handling-exceptions-and-errors
Just to quote it, you need to check error with instanceof
call to determine what type of error it is, what properties it has, and handle it accordingly.
For example PrismaClientKnownRequestError
has code
property, but PrismaClientValidationError
does not and so on.
Example:
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
}
Regarding your code, we can't really know what res.json(err);
does under the hood, hard to tell why it only returns clientVersion
, but just console.log
should call .toString()
method on the error object and you should get much more info about it, not just clientVersion
Upvotes: 3