Is there an error code for attempting to create an...
# orm-help
m
Is there an error code for attempting to create an object with a duplicate id (i.e. an id that is already associated with another object in the database)?
r
Hi @Mattia Romeo - yes there is, I hit this the other day .. one sec and I'll find it for you ..
Have some code too .. the
if (err instanceof Prisma.PrismaClientKnownRequestError)
ensures it is a prisma error object and you can then check if it's a
P2002
Copy code
try {
    const created = await prisma.xxx.create({data: data});

    if (created) {
      return "success";
    }
    return "not success";
  } catch (err) {
    if (err instanceof Prisma.PrismaClientKnownRequestError) {
      if (err.code === 'P2002') {
        logger.error('Unique constraint violation, xxx not be created');
        return 'Unique database constraint violation';
      }
    }

    return 'An unexpected error has occured';
  }
m
@Richard Ward Thanks so much! Github copilot actually suggested
P2002
as the error code but I wasn’t sure exactly what
Unique constraint failed
failed meant. Really appreciate the sample code too.
👍 1