3

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);
    }
  },
};
Gustavo Farias
  • 393
  • 5
  • 15

1 Answers1

3

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: '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
}

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

Danila
  • 15,606
  • 2
  • 35
  • 67
  • `console.log` doesn't have a different output, it's the same as `res.json(err)`. Regarding the error instances, you're right, `PrismaClientValidationError` doesn't have an error code, but it should come with a `message` property, as stated [here](https://www.prisma.io/docs/reference/api-reference/error-reference). This error message would be way better than `clientVersion` – Gustavo Farias Jan 25 '22 at 14:37
  • So you actually tried to `console.log(e.message)` and it was `undefined`? Or what do you mean? I've just tested it and it works as described in the docs – Danila Jan 25 '22 at 14:41
  • Yes, if I `console.log(err)`, I get the JSON I put on the question, and `console.log(err.message)` is `undefined` – Gustavo Farias Jan 25 '22 at 14:46
  • Docs says that error handling is incomplete for Mongo at this moment. Are you using it by chance? Maybe that's why some fields are missing, I haven't used it with Prisma yet, so can't tell. Or what db and what version of db are you using? If this is not the case then it seems like a bug and I suggest you to create an issue on Prisma Github page https://github.com/prisma/prisma, although they will probably ask for minimal reproduction example. – Danila Jan 25 '22 at 14:52
  • I'm using it with Postgres, I just found this github [issue](https://github.com/prisma/prisma/issues/10141). And yes, I think I'll have to create an issue, since my problem is quite similar but happens on client queries rather than raw queries – Gustavo Farias Jan 25 '22 at 14:59