prisma: Unable to issue instanceof Prisma.PrismaClientValidationError on known caught PrismaClientValidationError

Bug description

When an error is caught by the try catch statement, console.log(e) shows that the error is a PrismaClientValidationError

...
PrismaClientValidationError: 
Invalid `prisma.cardholder.create()` invocation:

{
  data: {
...

Yet running the caught e through a validation statement will not result in true, and so will not run the enclosed code of the statement.

try {
    const addCardholder = await db.cardholder.create({ data: cardholder });
} catch (e) {
    if (e instanceof Prisma.PrismaClientValidationError) {
        error = [true, e.message]; // this never is ran as the if statement results in false
    }
}

How to reproduce

  1. Send a DB record create statement with known invalid schema or values
  2. This will result in a PrismaClientValidationError
  3. Pass this through a try catch statement and try to use instanceof against the Prisma.PrismaClientValidationError type
  4. User preference for output statement, but this is definitely not running as the array remains its predefined values of [false, undefined]

Expected behavior

No response

Prisma information

db variable represented by db.server.ts

import { PrismaClient } from "@prisma/client";

let db: PrismaClient;

declare global {
  var __db: PrismaClient | undefined;
}

if (process.env.NODE_ENV === "production") {
  db = new PrismaClient();
  db.$connect();
} else {
  if (!global.__db) {
    global.__db = new PrismaClient();
    global.__db.$connect();
  }
  db = global.__db;
}

export { db };

Environment & setup

  • OS: macOS
  • Database: MySQL
  • Node.js version: 16.14.0, Remix 1.2.0

Prisma Version

prisma                  : 3.10.0
@prisma/client          : 3.10.0
Current platform        : darwin
Query Engine (Node-API) : libquery-engine 73e60b76d394f8d37d8ebd1f8918c79029f0db86 (at node_modules/@prisma/engines/libquery_engine-darwin.dylib.node)
Migration Engine        : migration-engine-cli 73e60b76d394f8d37d8ebd1f8918c79029f0db86 (at node_modules/@prisma/engines/migration-engine-darwin)
Introspection Engine    : introspection-core 73e60b76d394f8d37d8ebd1f8918c79029f0db86 (at node_modules/@prisma/engines/introspection-engine-darwin)
Format Binary           : prisma-fmt 73e60b76d394f8d37d8ebd1f8918c79029f0db86 (at node_modules/@prisma/engines/prisma-fmt-darwin)
Default Engines Hash    : 73e60b76d394f8d37d8ebd1f8918c79029f0db86
Studio                  : 0.458.0

About this issue

  • Original URL
  • State: open
  • Created 5 years ago
  • Reactions: 10
  • Comments: 21 (4 by maintainers)

Most upvoted comments

I’m using version 4.11.0 and I was facing the same issue, not sure why the direct import isn’t working but this seems to fix it:

import { Prisma } from '@prisma/client';

// ...

try {
 // ...
} catch (error) {
  if (error instanceof Prisma.PrismaClientKnownRequestError) {
    if (error.code === 'P2002') {
      // throw custom error;
    }
  } else {
    throw error;
  }
}

Same issue on Prisma 6.2.1, any work around?

Here’s the code I’m using, as a work around. It’s based on what was posted above:

import {
  PrismaClientKnownRequestError,
  PrismaClientValidationError,
} from '@prisma/client/runtime/library';

/**
 * Hack for a bug in PrismaClientKnownRequestError that prevents instanceof checks
 * https://github.com/prisma/prisma/issues/12128
 * @param error Any kind of actual error, object or otherwise
 * @returns Boolean indicating whether the error is a PrismaClientKnownRequestError
 */
export function isPrismaError(
  error: any,
): error is PrismaClientKnownRequestError {
  return error.constructor.name === PrismaClientKnownRequestError.name;
}

export function isPrismaValidationError(
  error: any,
): error is PrismaClientValidationError {
  return error.constructor.name === PrismaClientValidationError.name;
}

Not very pretty, and I need to expand it out for the other error types. I’m just using it as a stand-in until an actual fix is made.

Probably related, but still happening on 4.2.1:

I can’t do this, the if always returns false… on a try,catch of a prisma.$transaction

 if (error instanceOf Prisma.PrismaClientKnownRequestError) {
      if (error.code === "P2002") {
        throw new ApiError(400, "This instrument is already in this benchmark");
      }
    } else {
      throw error;
    }

Meanwhile I had to do this:

 } catch (error: any) {
    if (error.constructor.name === Prisma.PrismaClientKnownRequestError.name) {
      if (error.code === "P2002") {
        throw new ApiError(400, "This instrument is already in this benchmark");
      }
    } else {
      throw error;
    }
  }

Facing the same issue. Prisma version is 4.11.0. Sharing the example of code:

try {
    const category = await this.prisma.category.create({
        data: {
            category_icon: category_icon,
            category_name: category_name,
            category_slug: slugify(category_name),
        }
    });
    return category;
}
catch (error) {
    if (error instanceof PrismaClientKnownRequestError) {
    // always returns false, despite the fact that name of the error constructor is PrismaClientKnownRequestError
        if (error.code === 'P2002') {
            throw new BadRequestException(CATEGORY_ERRORS.ALREADY_EXISTS);
        }
    }
    // Working with other errors
}

Having exact same problem, cannot catch the exception to respond properly using nestJS


import { ArgumentsHost, Catch, ExceptionFilter, HttpStatus } from '@nestjs/common';
import { BaseExceptionFilter } from '@nestjs/core';
import { Prisma } from '@prisma/client';
import { PrismaClientValidationError } from '@prisma/client/runtime';
import { Response } from 'express'

@Catch(

  // prisma errors with .code
  Prisma.PrismaClientKnownRequestError,
  Prisma.NotFoundError,

  // insert failed
  Prisma.PrismaClientValidationError,

  // alias
  PrismaClientValidationError
  
)

export class PrismaClientExceptionFilter extends BaseExceptionFilter {
  catch(exception: (any), host: ArgumentsHost) {

    const ctx = host.switchToHttp();
    const response = ctx.getResponse<Response>();


    console.debug('I GOT U')
    if(exception.constructor.name === PrismaClientValidationError.name) {

      const status = HttpStatus.CONFLICT;
      const message = exception.message.replace(/\n/g, '');

      response.status(status).json({
        statusCode: status,
        message: message
      });

    }

Application just stops

Same issue on Prisma 6.2.1, any work around?

I am using prisma 4.11.0 and getting the same error

 if (error instanceof PrismaClientKnownRequestError) {
                console.log(error.code)
                if (error.code === 'P2002') {
                    throw new ForbiddenException('Email already exists')
                }
            }

In the above code instanceof PrismaClientKnownRequestError returns false

Downgrading to 4.8.1 solves the problem.

I just ran into this same issue with PrismaClientKnownRequestError in a Remix project with @prisma/client version 4.6.1.

After debugging a bit, it seems the issue only occurs when @prisma/client is included in serverDependenciesToBundle.

I think what’s happening is somehow when Remix is rebuilding the app on changes, the error object being thrown by Prisma is not an instance of the same instance of the PrismaClientKnownRequestError class.

If that’s confusing, consider that this code would print false because there are two different “instances” of class X:

function getInstance() {
  class X {}
  return new X()
}

console.log(getInstance().constructor === getInstance().constructor)
//=> false

While this would print true:

class X {}

function getInstance() {
  return new X()
}

console.log(getInstance().constructor === getInstance().constructor)
//=> true

Anyway, my solution was just to exclude @prisma/client from serverDependenciesToBundle and now the instanceof check works fine!

@BrendanRomanDev the snippet you are showing is not what @alethyst posted as solution. runtime module is our private API, it can change in any version without prior warning and you are not supposed to import directly from. Import Prisma namespace from @prisma/client module and use Prisma.PrismaClientKnownRequestError instead.

From my side upgrading from 4.2.1 to latest (4.8.1), fixed the issue on Vitest suite.