使用 Express 处理 Prisma 错误

Handle Prisma errors with Express

我在使用 ExpressJS 和 Prisma 进行错误处理时遇到了一些问题。每当发生 Prisma 异常时,我的整个 Node 应用程序都会崩溃,我必须重新启动它。我进行了一些谷歌搜索并查看了 Prisma Docs 的错误处理,但我找不到任何答案。

我知道我可以使用 trycatch,但这感觉没有必要,因为我可以使用错误处理程序更好地处理这个问题,尤其是在传递大量错误信息时通过 Prisma。

我试过像这样实现 Express 错误处理程序:

// index.ts

import errorHandler from "./middleware/errorHandler";
...
server.use(errorHandler);

// errorHandler.ts

import { NextFunction, Response } from "express";

// ts-ignore because next function is required for some weird reason
// @ts-ignore
const errorHandler = (err: any, _: any, res: Response, next: NextFunction) => {
    console.error(err.stack);
    res.status(500).send("Internal Server Error");
};

export default errorHandler;

这对正常错误工作正常,但不会对 Prisma 错误执行,而是只会使 Node 应用程序崩溃。

如何实现错误处理程序以便管理 Prisma Expections?

我今天 运行 遇到了这个问题,但我也找不到答案。我相信我们必须为 Prisma 异常编写我们自己的自定义错误处理程序,而不是抛出错误。

try {
  await prismaOperation();
} catch(e) {
  throw e; // avoid this which will crash our app
  /* Process Prisma error with error codes
     and prepare an appropriate error message
  */
  const error = prismaCustomErrorHandler(e);
  res.send(error); // Sending response instead of passing it to our default handler
}

此外,

// ts-ignore because next function is required for some weird reason

在 Express 中,错误处理函数有 4 个参数而不是 3 个:(err, req, res, next).

Express 将具有 3 个参数的中间件函数解释为 (req, res, next),这与省略第 4 个参数 (err, _, res) 不同。因此,Express 不会传递任何错误,你的 err 将是一个 req 对象,_ (req) 是一个 res 对象,而 res 是一个 next函数。

编辑:

...
const error = prismaCustomErrorHandler(e);
  res.send(error); // Sending response instead of passing it to our default handler
...

// Edit: Or you could process and pass the error using `next(error)` to default error handler.

上述方法不会使应用程序崩溃并且确实会发送响应。但是不管你用next还是res.send,都得处理错误。