An Interest In:
Web News this Week
- April 2, 2024
- April 1, 2024
- March 31, 2024
- March 30, 2024
- March 29, 2024
- March 28, 2024
- March 27, 2024
June 29, 2022 08:39 pm GMT
Original Link: https://dev.to/mk/nextjs-little-decorator-higher-order-function-to-handle-prisma-errors-e5j
Next.JS - little decorator (Higher Order Function) to handle Prisma errors
I am quite surprised I couldn't find any generic way to handle exception from prisma
client, so I wrote my own decorator.
I am just starting learning Next.js, so my approach could be very naive though, let me know if you see any improvements here.
It hides the error details for any other environment than dev
.
import { NextApiRequest, NextApiResponse } from "next";import { isDevEnv } from "./common";import { Prisma } from "@prisma/client";export function withPrismaError(request: (req: NextApiRequest, res: NextApiResponse) => unknown) { return async function (req: NextApiRequest, res: NextApiResponse) { try { await request(req, res); } catch (e) { if (e instanceof Prisma.PrismaClientKnownRequestError) { const errorResponse = { error: isDevEnv ? `${e.code} ${e.message}` : "prisma_error", }; return res.status(503).json(errorResponse); } return res.status(503).json({ error: true }); } };}
and the usage:
export default withPrismaError( async function handler(req: NextApiRequest, res: NextApiResponse) { const { email, password, url } = req.body; await registerUser(email, password, url); res.status(200).json({ success: true }); });
PS. ...and "hello guys", apparently today I am transitioned from "lurker" to blogger!
Original Link: https://dev.to/mk/nextjs-little-decorator-higher-order-function-to-handle-prisma-errors-e5j
Share this article:
Tweet
View Full Article
Dev To
An online community for sharing and discovering great ideas, having debates, and making friendsMore About this Source Visit Dev To