配置错误格式
默认情况下,Prisma 客户端使用 ANSI 转义字符 来漂亮地打印错误堆栈并提供有关如何解决问题的建议。虽然这在从终端使用 Prisma Client 时非常有用,但在 GraphQL API 等上下文中,你只需要最小的错误而不需要任何额外的格式。
¥By default, Prisma Client uses ANSI escape characters to pretty print the error stack and give recommendations on how to fix a problem. While this is very useful when using Prisma Client from the terminal, in contexts like a GraphQL API, you only want the minimal error without any additional formatting.
本页介绍如何使用 Prisma 客户端配置错误格式。
¥This page explains how error formatting can be configured with Prisma Client.
格式化级别
¥Formatting levels
有 3 个错误格式级别:
¥There are 3 error formatting levels:
-
漂亮的错误(默认):包括带有颜色的完整堆栈跟踪、代码的语法高亮以及扩展的错误消息以及问题的可能解决方案。
¥Pretty Error (default): Includes a full stack trace with colors, syntax highlighting of the code and extended error message with a possible solution for the problem.
-
无色错误:与漂亮错误相同,只是没有颜色。
¥Colorless Error: Same as pretty errors, just without colors.
-
最小误差:原始错误消息。
¥Minimal Error: The raw error message.
为了配置这些不同的错误格式级别,有两个选项:
¥In order to configure these different error formatting levels, there are two options:
-
通过环境变量设置配置选项
¥Setting the config options via environment variables
-
向
PrismaClient
构造函数提供配置选项¥Providing the config options to the
PrismaClient
constructor
通过环境变量格式化
¥Formatting via environment variables
-
NO_COLOR
:如果提供了此环境变量,则会从错误消息中去除颜色。因此你最终会得到一个无色错误。NO_COLOR
环境变量是 此处 描述的标准。¥
NO_COLOR
: If this env var is provided, colors are stripped from the error messages. Therefore you end up with a colorless error. TheNO_COLOR
environment variable is a standard described here. -
NODE_ENV=production
:如果环境变量NODE_ENV
设置为production
,则只会打印最小的错误。这使得在生产环境中更容易消化日志。¥
NODE_ENV=production
: If the env varNODE_ENV
is set toproduction
, only the minimal error will be printed. This allows for easier digestion of logs in production environments.
通过 PrismaClient
构造函数进行格式化
¥Formatting via the PrismaClient
constructor
或者,使用 PrismaClient
errorFormat
参数设置错误格式:
¥Alternatively, use the PrismaClient
errorFormat
parameter to set the error format:
const prisma = new PrismaClient({
errorFormat: 'pretty',
})