DEV Community

Cover image for Next.JS - little decorator (Higher Order Function) to handle Prisma errors
Mariusz
Mariusz

Posted on • Edited on

5 3

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 });
    }
  };
}

Enter fullscreen mode Exit fullscreen mode

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 });
  }
);
Enter fullscreen mode Exit fullscreen mode

PS. ...and "hello guys", apparently today I am transitioned from "lurker" to blogger!

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

While many AI coding tools operate as simple command-response systems, Qodo Gen 1.0 represents the next generation: autonomous, multi-step problem-solving agents that work alongside you.

Read full post

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more