#I want to create the try catch error handler for express application for the prisma

3 messages · Page 1 of 1 (latest)

atomic ether
#

like for unique i should be able to throw the clear message, all like the database error kind of message in want to throw the friendly error message

polar delta
#

Hey @atomic ether 👋

Do you mean you want to catch the errors thrown by Prisma and then throw your own custom error, right?

#

You can take reference from this error code guide here:
https://www.prisma.io/docs/reference/api-reference/error-reference

And create a middleware that shows custom error based on the `code1 attribute:

const errorHandler = (err, req, res, next) => {
  if (err instanceof prisma.Prisma.PrismaClientKnownRequestError) {
    // Handle known Prisma errors
    if (err.code === 'P2002') {
      return res.status(400).json({ error: 'Duplicate entry error' });
    }
  } else if (err instanceof prisma.Prisma.PrismaClientUnknownRequestError) {
    // Handle unknown Prisma errors
    return res.status(500).json({ error: 'An unknown database error occurred' });
  } else {
    // Handle other types of errors
    return res.status(500).json({ error: 'An unexpected error occurred' });
  }
};
Prisma

Prisma Client, Migrate, Introspection error message reference