Skip to content

Add model info to PrismaClientKnownRequestError #20724

Closed

Description

@EizFeren

Problem

I have global exception filter for NestJS, and it's catcher only have error instance of PrismaClientKnownRequestError. This execption filter needs somehow to know, what model is related to this error, e.g. to provide custom error message, related to model name.

Real example - trying to create user, but user with provided email exists in database. Exception filter uses error code (P2002) to detect this is unique constraint error or something else, but it still doesn't know what model it's related for.

Suggested solution

Add model name to error metadata, e.g.:

{
  meta: {
    model: 'User',
    target: [
      'email'
    ]
  }
}

Alternatives

Imho best approach will be attaching custom metadata for any query, e.g.:

prismaClient.user.create({
  data: {
    ...
  },
  customMetadata: {
    ... // any data engineer wants to attach
  },
});

Idk how it's possible and/or type safe, but this grants far more flexibility than current usage.

Activity

  1. EizFeren commented on Aug 17, 2023

    @EizFeren
    Author

    I've done somesing similar to described in Suggested solution, but... It's deprecated middleware

  2. SevInf commented on Aug 18, 2023

    @SevInf
    Contributor

    Hi @EizFeren.
    In meantime, instead of deprecated middleware, you can use query extension:

    
    const prisma = new PrismaClient().$extends({
      query: {
        $allModels: {
          async $allOperations({ query, args, model }) {
            try {
              return await query(args)
            } catch (error) {
               if (error instanceof PrismaClientKnownError) {
                  error.meta.model = model
               }
               throw error;
            }
        }
      }
    })
    
  3. EizFeren commented on Aug 18, 2023

    @EizFeren
    Author

    Ty, I'll use this. But, I think it's good idea to add model name to error metadata by default, this will be very usefull

  4. AikoRamalho commented on Nov 14, 2023

    @AikoRamalho
    Contributor

    Hey!

    I would love to work on it.

  5. SevInf commented on Nov 15, 2023

    @SevInf
    Contributor

    @AikoRamalho sure. This place in our code would probably be a good starting point. You can find our dev environment setup instructions here and testing instructions here.
    Looking forward to your contribution and let me know if you need help at any point.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    tech/typescripttopic: error handling

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions