Gestion des erreurs
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"}}}
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.
| Code | Description | HTTP code |
|---|---|---|
| BAD_REQUEST | The server cannot or will not process the request due to something that is perceived to be a client error. | 400 |
| UNAUTHORIZED | The client request has not been completed because it lacks valid authentication credentials for the requested resource. | 401 |
| FORBIDDEN | The server was unauthorized to access a required data source, such as a REST API. | 403 |
| NOT_FOUND | The server cannot find the requested resource. | 404 |
| TIMEOUT | The server would like to shut down this unused connection. | 408 |
| CONFLICT | The server request resource conflict with the current state of the target resource. | 409 |
| PRECONDITION_FAILED | Access to the target resource has been denied. | 412 |
| PAYLOAD_TOO_LARGE | Request entity is larger than limits defined by server. | 413 |
| METHOD_NOT_SUPPORTED | The server knows the request method, but the target resource doesn't support this method. | 405 |
| CLIENT_CLOSED_REQUEST | Access to the resource has been denied. | 499 |
| INTERNAL_SERVER_ERROR | An unspecified error occurred. | 500 |
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.tstsimport * as trpc from '@trpc/server';const appRouter = trpc.router().query('hello', {resolve: () => {throw new trpc.TRPCError({code: 'INTERNAL_SERVER_ERROR',message: 'An unexpected error occurred, please try again later.',// optional: pass the original error to retain stack tracecause: theError,});},});// [...]
server.tstsimport * as trpc from '@trpc/server';const appRouter = trpc.router().query('hello', {resolve: () => {throw new trpc.TRPCError({code: 'INTERNAL_SERVER_ERROR',message: 'An unexpected error occurred, please try again later.',// optional: pass the original error to retain stack tracecause: theError,});},});// [...]
Produit 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 ou modifier les erreurs.
pages/api/trpc/[trpc].tstsexport default trpcNext.createNextApiHandler({// ...onError({ error, type, path, input, ctx, req }) {console.error('Error:', error);if (error.code === 'INTERNAL_SERVER_ERROR') {// send to bug reporting}},});
pages/api/trpc/[trpc].tstsexport default trpcNext.createNextApiHandler({// ...onError({ error, type, path, input, ctx, req }) {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{error: TRPCError; // the original errortype: 'query' | 'mutation' | 'subscription' | 'unknown';path: string | undefined; // path of the procedure that was triggeredinput: unknown;ctx: Context | undefined;req: BaseRequest; // request object}
ts{error: TRPCError; // the original errortype: 'query' | 'mutation' | 'subscription' | 'unknown';path: string | undefined; // path of the procedure that was triggeredinput: unknown;ctx: Context | undefined;req: BaseRequest; // request object}