Aller au contenu principal
Version : 11.x

Gestion des erreurs

Traduction Bêta Non Officielle

Cette page a été traduite par PageTurner AI (bêta). Non approuvée officiellement par le projet. Vous avez trouvé une erreur ? Signaler un problème →

Lorsqu'une erreur survient dans une procédure, tRPC renvoie au client un objet contenant une propriété "error". Cette propriété inclut toutes les informations nécessaires pour traiter l'erreur côté client.

Voici un exemple de réponse d'erreur causée par une entrée de requête invalide :

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

Traces de la pile en production

Par défaut, tRPC inclut error.data.stack uniquement lorsque isDev est true.
initTRPC.create() définit isDev sur process.env.NODE_ENV !== 'production' par défaut.
Si vous avez besoin d'un comportement déterministe entre les environnements d'exécution, remplacez isDev manuellement.

server.ts
ts
import { initTRPC } from '@trpc/server';
 
const t = initTRPC.create({ isDev: false });
server.ts
ts
import { initTRPC } from '@trpc/server';
 
const t = initTRPC.create({ isDev: false });

Si vous avez besoin d'un contrôle plus strict sur les champs d'erreur renvoyés, utilisez le formatage des erreurs.

Codes d'erreur

tRPC définit une liste de codes d'erreur représentant différents types d'erreurs, chacun associé à un code HTTP distinct.

CodeDescriptionHTTP code
PARSE_ERRORInvalid JSON was received by the server, or an error occurred while parsing the request.400
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 client is not authorized to access the requested resource.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 request conflicts 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_REQUESTThe client closed the connection before the server finished responding.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 expose une fonction utilitaire, getHTTPStatusCodeFromError, pour extraire le code HTTP de l'erreur :

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

Un exemple complet du fonctionnement de la gestion des erreurs dans un contexte serveur est disponible dans la documentation des appels serveur.

Lever des erreurs

tRPC fournit une sous-classe d'erreur, TRPCError, que vous pouvez utiliser pour représenter une erreur survenue dans une procédure.

Par exemple, lever cette erreur :

server.ts
ts
import { initTRPC, TRPCError } from '@trpc/server';
 
const t = initTRPC.create();
 
const theError = new Error('something went wrong');
 
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 theError = new Error('something went wrong');
 
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,
});
}),
});
 
// [...]

Résulte en la réponse suivante :

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

Traitement des erreurs

Toutes les erreurs survenant dans une procédure passent par la méthode onError avant d'être envoyées au client. Vous pouvez y gérer les erreurs (pour les modifier, consultez formatage des erreurs).

server.ts
ts
import { createHTTPServer } from '@trpc/server/adapters/standalone';
import { appRouter } from './router';
 
const server = createHTTPServer({
router: appRouter,
onError(opts) {
const { error, type, path, input, ctx, req } = opts;
console.error('Error:', error);
if (error.code === 'INTERNAL_SERVER_ERROR') {
// send to bug reporting
}
},
});
server.ts
ts
import { createHTTPServer } from '@trpc/server/adapters/standalone';
import { appRouter } from './router';
 
const server = createHTTPServer({
router: appRouter,
onError(opts) {
const { error, type, path, input, ctx, req } = opts;
console.error('Error:', error);
if (error.code === 'INTERNAL_SERVER_ERROR') {
// send to bug reporting
}
},
});

Le paramètre onError est un objet contenant toutes les informations sur l'erreur et son contexte d'apparition :

ts
interface OnErrorOpts {
error: TRPCError;
type: 'query' | 'mutation' | 'subscription' | 'unknown';
path: string | undefined;
input: unknown;
ctx: unknown;
req: Request;
}
ts
interface OnErrorOpts {
error: TRPCError;
type: 'query' | 'mutation' | 'subscription' | 'unknown';
path: string | undefined;
input: unknown;
ctx: unknown;
req: Request;
}