#I want to create the try catch error handler for express application for the prisma
3 messages · Page 1 of 1 (latest)
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' });
}
};