Felhantering
Denna sida har översatts av PageTurner AI (beta). Inte officiellt godkänd av projektet. Hittade du ett fel? Rapportera problem →
När ett fel uppstår i en procedur svarar tRPC till klienten med ett objekt som innehåller en "error"-egenskap. Denna egenskap innehåller all information du behöver för att hantera felet i klienten.
Här är ett exempel på felsvar orsakat av felaktig indata i en förfrågan:
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"}}}
Stackspår i produktion
Som standard inkluderar tRPC error.data.stack endast när isDev är true.
initTRPC.create() sätter isDev till process.env.NODE_ENV !== 'production' som standard.
Om du behöver deterministiskt beteende mellan olika körningsmiljöer, åsidosätt isDev manuellt.
server.tstsimport {initTRPC } from '@trpc/server';constt =initTRPC .create ({isDev : false });
server.tstsimport {initTRPC } from '@trpc/server';constt =initTRPC .create ({isDev : false });
Om du behöver striktare kontroll över vilka feldata som returneras, använd error formatting.
Felkoder
tRPC definierar en lista med felkoder där varje kod representerar en olika typ av fel och svarar med ett annat HTTP-statuskod.
| Code | Description | HTTP code |
|---|---|---|
| PARSE_ERROR | Invalid JSON was received by the server, or an error occurred while parsing the request. | 400 |
| 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 |
| PAYMENT_REQUIRED | The client request requires payment to access the requested resource. | 402 |
| FORBIDDEN | The client is not authorized to access the requested resource. | 403 |
| NOT_FOUND | The server cannot find the requested resource. | 404 |
| METHOD_NOT_SUPPORTED | The server knows the request method, but the target resource doesn't support this method. | 405 |
| TIMEOUT | The server would like to shut down this unused connection. | 408 |
| CONFLICT | The request conflicts 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 |
| UNSUPPORTED_MEDIA_TYPE | The server refuses to accept the request because the payload format is in an unsupported format. | 415 |
| UNPROCESSABLE_CONTENT | The server understands the request method, and the request entity is correct, but the server was unable to process it. | 422 |
| PRECONDITION_REQUIRED | The 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_REQUESTS | The rate limit has been exceeded or too many requests are being sent to the server. | 429 |
| CLIENT_CLOSED_REQUEST | The client closed the connection before the server finished responding. | 499 |
| INTERNAL_SERVER_ERROR | An unspecified error occurred. | 500 |
| NOT_IMPLEMENTED | The server does not support the functionality required to fulfill the request. | 501 |
| BAD_GATEWAY | The server received an invalid response from the upstream server. | 502 |
| SERVICE_UNAVAILABLE | The server is not ready to handle the request. | 503 |
| GATEWAY_TIMEOUT | The server did not get a response in time from the upstream server that it needed in order to complete the request. | 504 |
tRPC tillhandahåller hjälpfunktionen getHTTPStatusCodeFromError för att extrahera HTTP-statuskoden från felet:
tsimport {getHTTPStatusCodeFromError } from '@trpc/server/http';// Example error you might get if your input validation failsconsterror :TRPCError = {name : 'TRPCError',code : 'BAD_REQUEST',message : '"password" must be at least 4 characters',};if (error instanceofTRPCError ) {consthttpCode =getHTTPStatusCodeFromError (error );console .log (httpCode ); // 400}
tsimport {getHTTPStatusCodeFromError } from '@trpc/server/http';// Example error you might get if your input validation failsconsterror :TRPCError = {name : 'TRPCError',code : 'BAD_REQUEST',message : '"password" must be at least 4 characters',};if (error instanceofTRPCError ) {consthttpCode =getHTTPStatusCodeFromError (error );console .log (httpCode ); // 400}
Ett fullständigt exempel på hur felhantering fungerar i en servermiljö finns i dokumentationen för Server Side Calls.
Kasta fel
tRPC tillhandahåller en felunderklass, TRPCError, som du kan använda för att representera ett fel som uppstått i en procedur.
Exempelvis ger följande felkastning:
server.tstsimport {initTRPC ,TRPCError } from '@trpc/server';constt =initTRPC .create ();consttheError = newError ('something went wrong');constappRouter =t .router ({hello :t .procedure .query (() => {throw newTRPCError ({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 {initTRPC ,TRPCError } from '@trpc/server';constt =initTRPC .create ();consttheError = newError ('something went wrong');constappRouter =t .router ({hello :t .procedure .query (() => {throw newTRPCError ({code : 'INTERNAL_SERVER_ERROR',message : 'An unexpected error occurred, please try again later.',// optional: pass the original error to retain stack tracecause :theError ,});}),});// [...]
Resulterar i följande svar:
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"}}}
Hantera fel
Alla fel som uppstår i en procedur passerar genom onError-metoden innan de skickas till klienten. Här kan du hantera fel (för att ändra felrepresentation, se error formatting).
server.tstsimport {createHTTPServer } from '@trpc/server/adapters/standalone';import {appRouter } from './router';constserver =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.tstsimport {createHTTPServer } from '@trpc/server/adapters/standalone';import {appRouter } from './router';constserver =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}},});
onError-parametern är ett objekt som innehåller all information om felet och den kontext det uppstod i:
tsinterfaceOnErrorOpts {error :TRPCError ;type : 'query' | 'mutation' | 'subscription' | 'unknown';path : string | undefined;input : unknown;ctx : unknown;req :Request ;}
tsinterfaceOnErrorOpts {error :TRPCError ;type : 'query' | 'mutation' | 'subscription' | 'unknown';path : string | undefined;input : unknown;ctx : unknown;req :Request ;}