Skip to main content
Version: 10.x

错误处理

每当过程中发生错误时,tRPC 都会使用包含 "error" 属性的对象响应客户端。该属性包含处理客户端错误所需的所有信息。

¥Whenever an error occurs in a procedure, tRPC responds to the client with an object that includes an "error" property. This property contains all the information that you need to handle the error in the client.

以下是由错误的请求输入引起的错误响应示例:

¥Here's an example error response caused by a bad request input:

json
{
"id": null,
"error": {
"message": "\"password\" must be at least 4 characters",
"code": -32600,
"data": {
"code": "BAD_REQUEST",
"httpStatus": 400,
"stack": "...",
"path": "user.changepassword"
}
}
}
json
{
"id": null,
"error": {
"message": "\"password\" must be at least 4 characters",
"code": -32600,
"data": {
"code": "BAD_REQUEST",
"httpStatus": 400,
"stack": "...",
"path": "user.changepassword"
}
}
}

注意:返回的堆栈跟踪仅在开发环境中可用。

¥Note: the returned stack trace is only available in the development environment.

错误代码

¥Error codes

tRPC 定义了错误代码列表,每个错误代码代表不同类型的错误并使用不同的 HTTP 代码进行响应。

¥tRPC defines a list of error codes that each represent a different type of error and response with a different HTTP code.

代码描述HTTP 代码
错误的请求由于被认为是客户端错误,服务器无法或不会处理请求。400
UNAUTHORIZED客户端请求尚未完成,因为它缺少所请求资源的有效身份验证凭据。401
FORBIDDEN服务器未经授权访问所需的数据源,例如 REST API。403
未找到服务器找不到所请求的资源。404
TIMEOUT服务器想要关闭这个未使用的连接。408
CONFLICT服务器请求资源与目标资源的当前状态冲突。409
先决条件 _ 失败对目标资源的访问已被拒绝。412
PAYLOAD_TOO_LARGE请求实体大于服务器定义的限制。413
METHOD_NOT_SUPPORTED服务器知道请求方法,但目标资源不支持该方法。405
无法处理的内容服务器理解请求方法,请求实体正确,但服务器无法处理。422
TOO_MANY_REQUESTS已超出速率限制或向服务器发送的请求过多。429
CLIENT_CLOSED_REQUEST对资源的访问已被拒绝。499
内部服务器错误发生未指定的错误。500

tRPC 公开了一个辅助函数 getHTTPStatusCodeFromError,以帮助你从错误中提取 HTTP 代码:

¥tRPC exposes a helper function, getHTTPStatusCodeFromError, to help you extract the HTTP code from the error:

ts
import { getHTTPStatusCodeFromError } from '@trpc/server/http';
 
// Example error you might get if your input validation fails
const error: TRPCError = {
name: 'TRPCError',
code: 'BAD_REQUEST',
message: '"password" must be at least 4 characters',
};
 
if (error instanceof TRPCError) {
const httpCode = getHTTPStatusCodeFromError(error);
console.log(httpCode); // 400
}
ts
import { getHTTPStatusCodeFromError } from '@trpc/server/http';
 
// Example error you might get if your input validation fails
const error: TRPCError = {
name: 'TRPCError',
code: 'BAD_REQUEST',
message: '"password" must be at least 4 characters',
};
 
if (error instanceof TRPCError) {
const httpCode = getHTTPStatusCodeFromError(error);
console.log(httpCode); // 400
}
提示

有一个完整的示例说明了如何在 服务器端调用文档 中的 Next.js API 端点中使用它。

¥There's a full example of how this could be used in a Next.js API endpoint in the Server Side Calls docs.

投掷错误

¥Throwing errors

tRPC 提供了一个错误子类 TRPCError,你可以使用它来表示过程内发生的错误。

¥tRPC provides an error subclass, TRPCError, which you can use to represent an error that occurred inside a procedure.

例如,抛出这个错误:

¥For example, throwing this error:

server.ts
ts
import { initTRPC, TRPCError } from '@trpc/server';
const t = initTRPC.create();
const appRouter = t.router({
hello: t.procedure.query(() => {
throw new TRPCError({
code: 'INTERNAL_SERVER_ERROR',
message: 'An unexpected error occurred, please try again later.',
// optional: pass the original error to retain stack trace
cause: theError,
});
}),
});
// [...]
server.ts
ts
import { initTRPC, TRPCError } from '@trpc/server';
const t = initTRPC.create();
const appRouter = t.router({
hello: t.procedure.query(() => {
throw new TRPCError({
code: 'INTERNAL_SERVER_ERROR',
message: 'An unexpected error occurred, please try again later.',
// optional: pass the original error to retain stack trace
cause: theError,
});
}),
});
// [...]

结果如下:

¥Results to the following response:

json
{
"id": null,
"error": {
"message": "An unexpected error occurred, please try again later.",
"code": -32603,
"data": {
"code": "INTERNAL_SERVER_ERROR",
"httpStatus": 500,
"stack": "...",
"path": "hello"
}
}
}
json
{
"id": null,
"error": {
"message": "An unexpected error occurred, please try again later.",
"code": -32603,
"data": {
"code": "INTERNAL_SERVER_ERROR",
"httpStatus": 500,
"stack": "...",
"path": "hello"
}
}
}

处理错误

¥Handling errors

过程中发生的所有错误在发送到客户端之前都会经过 onError 方法。你可以在这里处理或更改错误。

¥All errors that occur in a procedure go through the onError method before being sent to the client. Here you can handle or change errors.

pages/api/trpc/[trpc].ts
ts
export default trpcNext.createNextApiHandler({
// ...
onError(opts) {
const { error, type, path, input, ctx, req } = opts;
console.error('Error:', error);
if (error.code === 'INTERNAL_SERVER_ERROR') {
// send to bug reporting
}
},
});
pages/api/trpc/[trpc].ts
ts
export default trpcNext.createNextApiHandler({
// ...
onError(opts) {
const { error, type, path, input, ctx, req } = opts;
console.error('Error:', error);
if (error.code === 'INTERNAL_SERVER_ERROR') {
// send to bug reporting
}
},
});

onError 参数是一个对象,其中包含有关错误及其发生上下文的所有信息:

¥The onError parameter is an object that contains all information about the error and the context it occurs in:

ts
{
error: TRPCError; // the original error
type: 'query' | 'mutation' | 'subscription' | 'unknown';
path: string | undefined; // path of the procedure that was triggered
input: unknown;
ctx: Context | undefined;
req: BaseRequest; // request object
}
ts
{
error: TRPCError; // the original error
type: 'query' | 'mutation' | 'subscription' | 'unknown';
path: string | undefined; // path of the procedure that was triggered
input: unknown;
ctx: Context | undefined;
req: BaseRequest; // request object
}