Saltar al contenido principal
Versión: 11.x

Manejo de errores

Traducción Beta No Oficial

Esta página fue traducida por PageTurner AI (beta). No está respaldada oficialmente por el proyecto. ¿Encontraste un error? Reportar problema →

Siempre que ocurre un error en un procedimiento, tRPC responde al cliente con un objeto que incluye una propiedad "error". Esta propiedad contiene toda la información que necesitas para manejar el error en el cliente.

Aquí tienes un ejemplo de respuesta de error causada por una entrada de solicitud incorrecta:

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"
}
}
}

Nota: la traza de pila devuelta solo está disponible en el entorno de desarrollo.

Códigos de error

tRPC define una lista de códigos de error donde cada uno representa un tipo diferente de error y responde con un código HTTP distinto.

CodeDescriptionHTTP code
BAD_REQUESTThe server cannot or will not process the request due to something that is perceived to be a client error.400
UNAUTHORIZEDThe client request has not been completed because it lacks valid authentication credentials for the requested resource.401
PAYMENT_REQUIREDThe client request requires payment to access the requested resource.402
FORBIDDENThe server was unauthorized to access a required data source, such as a REST API.403
NOT_FOUNDThe server cannot find the requested resource.404
METHOD_NOT_SUPPORTEDThe server knows the request method, but the target resource doesn't support this method.405
TIMEOUTThe server would like to shut down this unused connection.408
CONFLICTThe server request resource conflict with the current state of the target resource.409
PRECONDITION_FAILEDAccess to the target resource has been denied.412
PAYLOAD_TOO_LARGERequest entity is larger than limits defined by server.413
UNSUPPORTED_MEDIA_TYPEThe server refuses to accept the request because the payload format is in an unsupported format.415
UNPROCESSABLE_CONTENTThe server understands the request method, and the request entity is correct, but the server was unable to process it.422
PRECONDITION_REQUIREDThe server cannot process the request because a required precondition header (such as If-Match) is missing. When a precondition header does not match the server-side state, the response should be 412 Precondition Failed.428
TOO_MANY_REQUESTSThe rate limit has been exceeded or too many requests are being sent to the server.429
CLIENT_CLOSED_REQUESTAccess to the resource has been denied.499
INTERNAL_SERVER_ERRORAn unspecified error occurred.500
NOT_IMPLEMENTEDThe server does not support the functionality required to fulfill the request.501
BAD_GATEWAYThe server received an invalid response from the upstream server.502
SERVICE_UNAVAILABLEThe server is not ready to handle the request.503
GATEWAY_TIMEOUTThe server did not get a response in time from the upstream server that it needed in order to complete the request.504

tRPC expone una función auxiliar, getHTTPStatusCodeFromError, para ayudarte a extraer el código HTTP del 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
}
consejo

Hay un ejemplo completo de cómo usar esto en un endpoint API de Next.js en la documentación de Llamadas del lado del servidor.

Lanzar errores

tRPC proporciona una subclase de error, TRPCError, que puedes usar para representar un error ocurrido dentro de un procedimiento.

Por ejemplo, al lanzar este 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,
});
}),
});
// [...]

Se obtiene la siguiente respuesta:

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"
}
}
}

Manejo de errores

Todos los errores que ocurren en un procedimiento pasan por el método onError antes de enviarse al cliente. Aquí puedes manejar errores (para modificar errores, consulta formateo de errores).

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

El parámetro onError es un objeto que contiene toda la información sobre el error y el contexto en el que ocurre:

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
}