@trpc/server 11.22.2-canary.7.c01346ec8 → 11.23.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (114) hide show
  1. package/README.md +0 -8
  2. package/dist/adapters/aws-lambda/index.cjs +1 -1
  3. package/dist/adapters/aws-lambda/index.d.cts.map +1 -1
  4. package/dist/adapters/aws-lambda/index.d.mts.map +1 -1
  5. package/dist/adapters/aws-lambda/index.mjs +1 -1
  6. package/dist/adapters/aws-lambda/index.mjs.map +1 -1
  7. package/dist/adapters/express.cjs +1 -1
  8. package/dist/adapters/express.mjs +1 -1
  9. package/dist/adapters/express.mjs.map +1 -1
  10. package/dist/adapters/fastify/index.cjs +3 -3
  11. package/dist/adapters/fastify/index.mjs +3 -3
  12. package/dist/adapters/fetch/index.cjs +1 -1
  13. package/dist/adapters/fetch/index.mjs +1 -1
  14. package/dist/adapters/next-app-dir.mjs.map +1 -1
  15. package/dist/adapters/next.cjs +1 -1
  16. package/dist/adapters/next.mjs +1 -1
  17. package/dist/adapters/next.mjs.map +1 -1
  18. package/dist/adapters/node-http/index.cjs +1 -1
  19. package/dist/adapters/node-http/index.mjs +1 -1
  20. package/dist/adapters/standalone.cjs +9 -3
  21. package/dist/adapters/standalone.d.cts +0 -1
  22. package/dist/adapters/standalone.d.cts.map +1 -1
  23. package/dist/adapters/standalone.d.mts +0 -1
  24. package/dist/adapters/standalone.d.mts.map +1 -1
  25. package/dist/adapters/standalone.mjs +9 -3
  26. package/dist/adapters/standalone.mjs.map +1 -1
  27. package/dist/adapters/ws.cjs +1 -1
  28. package/dist/adapters/ws.mjs +1 -1
  29. package/dist/asyncGeneratorDelegate-FcEJT04i.mjs.map +1 -1
  30. package/dist/codes-C9N0z0an.mjs.map +1 -1
  31. package/dist/getErrorShape-zlj81BiC.mjs.map +1 -1
  32. package/dist/http.cjs +1 -1
  33. package/dist/http.mjs +1 -1
  34. package/dist/initTRPC-RMeQIy9H.mjs.map +1 -1
  35. package/dist/{node-http-B5jkpWn7.mjs → node-http-ChhZEv1k.mjs} +2 -2
  36. package/dist/node-http-ChhZEv1k.mjs.map +1 -0
  37. package/dist/{node-http-BZ0HlzkC.cjs → node-http-X8RiQEuH.cjs} +1 -1
  38. package/dist/parseTRPCMessage-CJ4DJVBp.mjs.map +1 -1
  39. package/dist/{resolveResponse-b9D_SrLs.cjs → resolveResponse-CoGjFxK0.cjs} +8 -4
  40. package/dist/{resolveResponse-DH5L33sC.mjs → resolveResponse-DksrxZ2k.mjs} +9 -5
  41. package/dist/resolveResponse-DksrxZ2k.mjs.map +1 -0
  42. package/dist/unstable-core-do-not-import-B8epiErP.d.cts.map +1 -1
  43. package/dist/unstable-core-do-not-import-Dbo98mkh.d.mts.map +1 -1
  44. package/dist/unstable-core-do-not-import.cjs +1 -1
  45. package/dist/unstable-core-do-not-import.mjs +1 -1
  46. package/dist/unstable-core-do-not-import.mjs.map +1 -1
  47. package/dist/{ws-83TNWW-W.cjs → ws-7qWW7Uec.cjs} +2 -2
  48. package/dist/{ws-DJ2SSChC.mjs → ws-BYfo-HED.mjs} +3 -3
  49. package/dist/ws-BYfo-HED.mjs.map +1 -0
  50. package/package.json +9 -12
  51. package/skills/adapter-aws-lambda/SKILL.md +152 -134
  52. package/skills/adapter-express/SKILL.md +127 -113
  53. package/skills/adapter-fastify/SKILL.md +228 -136
  54. package/skills/adapter-fetch/SKILL.md +388 -111
  55. package/skills/adapter-standalone/SKILL.md +184 -94
  56. package/skills/auth/SKILL.md +327 -202
  57. package/skills/auth/references/client-cors.md +29 -0
  58. package/skills/caching/SKILL.md +58 -148
  59. package/skills/error-handling/SKILL.md +280 -174
  60. package/skills/middlewares/SKILL.md +320 -121
  61. package/skills/non-json-content-types/SKILL.md +149 -168
  62. package/skills/server-setup/SKILL.md +355 -253
  63. package/skills/server-setup/references/server-context.md +219 -0
  64. package/skills/server-setup/references/server-merging-routers.md +141 -0
  65. package/skills/server-setup/references/server-metadata.md +105 -0
  66. package/skills/server-setup/references/server-procedures.md +172 -0
  67. package/skills/server-setup/references/server-routers.md +123 -0
  68. package/skills/server-side-calls/SKILL.md +247 -152
  69. package/skills/service-oriented-architecture/SKILL.md +81 -177
  70. package/skills/subscriptions/SKILL.md +341 -297
  71. package/skills/subscriptions/references/client-links-httpSubscriptionLink.md +404 -0
  72. package/skills/subscriptions/references/client-links-wsLink.md +122 -0
  73. package/skills/subscriptions/references/server-websockets.md +297 -0
  74. package/skills/trpc-router/SKILL.md +156 -86
  75. package/skills/validators/SKILL.md +384 -128
  76. package/src/adapters/aws-lambda/getPlanner.ts +4 -3
  77. package/src/adapters/aws-lambda/index.ts +2 -1
  78. package/src/adapters/express.ts +1 -1
  79. package/src/adapters/next-app-dir/nextAppDirCaller.ts +4 -4
  80. package/src/adapters/next-app-dir/rethrowNextErrors.ts +1 -1
  81. package/src/adapters/next.ts +1 -1
  82. package/src/adapters/node-http/incomingMessageToRequest.ts +1 -1
  83. package/src/adapters/node-http/nodeHTTPRequestHandler.ts +1 -1
  84. package/src/adapters/node-http/types.ts +1 -1
  85. package/src/adapters/node-http/writeResponse.ts +1 -1
  86. package/src/adapters/standalone.ts +12 -6
  87. package/src/adapters/ws.ts +5 -5
  88. package/src/unstable-core-do-not-import/clientish/inferrable.ts +4 -1
  89. package/src/unstable-core-do-not-import/clientish/serialize.ts +4 -4
  90. package/src/unstable-core-do-not-import/error/TRPCError.ts +3 -3
  91. package/src/unstable-core-do-not-import/http/formDataToObject.ts +1 -1
  92. package/src/unstable-core-do-not-import/http/getHTTPStatusCode.ts +1 -1
  93. package/src/unstable-core-do-not-import/http/resolveResponse.ts +13 -2
  94. package/src/unstable-core-do-not-import/procedure.ts +5 -2
  95. package/src/unstable-core-do-not-import/procedureBuilder.ts +3 -2
  96. package/src/unstable-core-do-not-import/rootConfig.ts +2 -2
  97. package/src/unstable-core-do-not-import/router.ts +5 -2
  98. package/src/unstable-core-do-not-import/rpc/envelopes.ts +3 -2
  99. package/src/unstable-core-do-not-import/stream/jsonl.ts +2 -1
  100. package/src/unstable-core-do-not-import/stream/sse.types.ts +1 -1
  101. package/src/unstable-core-do-not-import/stream/utils/asyncIterable.ts +1 -1
  102. package/src/unstable-core-do-not-import/stream/utils/createDeferred.ts +1 -1
  103. package/src/unstable-core-do-not-import/stream/utils/disposable.ts +6 -6
  104. package/src/unstable-core-do-not-import/stream/utils/mergeAsyncIterables.ts +2 -2
  105. package/src/unstable-core-do-not-import/stream/utils/withPing.ts +3 -1
  106. package/src/unstable-core-do-not-import/transformer.ts +4 -1
  107. package/src/unstable-core-do-not-import/types.ts +3 -2
  108. package/src/unstable-core-do-not-import/utils.ts +1 -1
  109. package/src/vendor/standard-schema-v1/spec.ts +2 -2
  110. package/src/vendor/unpromise/unpromise.ts +1 -1
  111. package/bin/intent.js +0 -20
  112. package/dist/node-http-B5jkpWn7.mjs.map +0 -1
  113. package/dist/resolveResponse-DH5L33sC.mjs.map +0 -1
  114. package/dist/ws-DJ2SSChC.mjs.map +0 -1
@@ -1,111 +1,166 @@
1
1
  ---
2
2
  name: error-handling
3
- description: >
4
- Throw typed errors with TRPCError and error codes (NOT_FOUND, UNAUTHORIZED,
5
- BAD_REQUEST, INTERNAL_SERVER_ERROR), configure errorFormatter for client-side
6
- Zod error display, handle errors globally with onError callback, map tRPC errors
7
- to HTTP status codes with getHTTPStatusCodeFromError().
8
- type: core
9
- library: trpc
10
- library_version: '11.16.0'
3
+ description: Throw typed errors with TRPCError and error codes (NOT_FOUND, UNAUTHORIZED, FORBIDDEN, BAD_REQUEST, INTERNAL_SERVER_ERROR), configure errorFormatter for client-side Zod error display or to hide internal error messages, format errors per procedure with .errors(), handle errors globally with the adapter's onError callback, map tRPC errors to HTTP status codes with getHTTPStatusCodeFromError(), control stack traces with isDev.
11
4
  requires:
12
5
  - server-setup
13
6
  sources:
14
- - 'trpc/trpc:www/docs/server/error-handling.md'
15
- - 'trpc/trpc:www/docs/server/error-formatting.md'
16
- - 'trpc/trpc:packages/server/src/unstable-core-do-not-import/error/TRPCError.ts'
7
+ - www/v11/docs/server/error-handling.md
8
+ - www/v11/docs/server/error-formatting.md
9
+ metadata:
10
+ type: core
11
+ library: trpc
12
+ library_version: 11.23.0
17
13
  ---
18
14
 
19
- # tRPC -- Error Handling
15
+ <!-- Generated from www/v11/docs/server/error-handling.md by www/build/skills.ts. Edit the docs instead. -->
20
16
 
21
- ## Setup
17
+ # Error Handling
22
18
 
23
- ```ts
24
- // server/trpc.ts
25
- import { initTRPC } from '@trpc/server';
26
- import { ZodError } from 'zod';
19
+ From https://trpc.io/docs/server/error-handling
27
20
 
28
- const t = initTRPC.create({
29
- errorFormatter({ shape, error }) {
30
- return {
31
- ...shape,
32
- data: {
33
- ...shape.data,
34
- zodError:
35
- error.code === 'BAD_REQUEST' && error.cause instanceof ZodError
36
- ? error.cause.flatten()
37
- : null,
38
- },
39
- };
40
- },
41
- });
21
+ 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.
22
+
23
+ Here's an example error response caused by a bad request input:
42
24
 
43
- export const router = t.router;
44
- export const publicProcedure = t.procedure;
25
+ ```json
26
+ {
27
+ "id": null,
28
+ "error": {
29
+ "message": "\"password\" must be at least 4 characters",
30
+ "code": -32600,
31
+ "data": {
32
+ "code": "BAD_REQUEST",
33
+ "httpStatus": 400,
34
+ "stack": "...",
35
+ "path": "user.changepassword"
36
+ }
37
+ }
38
+ }
45
39
  ```
46
40
 
47
- ## Core Patterns
48
-
49
- ### Throwing typed errors from procedures
50
-
51
- ```ts
52
- import { TRPCError } from '@trpc/server';
53
- import { z } from 'zod';
54
- import { publicProcedure, router } from './trpc';
55
-
56
- export const appRouter = router({
57
- userById: publicProcedure
58
- .input(z.object({ id: z.string() }))
59
- .query(({ input }) => {
60
- const user = getUserFromDb(input.id);
61
- if (!user) {
62
- throw new TRPCError({
63
- code: 'NOT_FOUND',
64
- message: `User with id ${input.id} not found`,
65
- });
66
- }
67
- return user;
68
- }),
69
- });
41
+ ## Stack traces in production
42
+
43
+ By default, tRPC includes `error.data.stack` only when [`isDev`](https://trpc.io/docs/server/routers#initialize-trpc) is `true`.
44
+ `initTRPC.create()` sets `isDev` to `process.env.NODE_ENV !== 'production'` by default.
45
+ If you need deterministic behavior across runtimes, override `isDev` manually.
46
+
47
+ ```ts no-check title="server.ts"
48
+ import { initTRPC } from '@trpc/server';
49
+
50
+ const t = initTRPC.create({ isDev: false });
51
+ ```
52
+
53
+ If you need stricter control over which error fields are returned, use [error formatting](https://trpc.io/docs/server/error-formatting).
54
+
55
+ ## Error codes
56
+
57
+ tRPC defines a list of error codes that each represent a different type of error and response with a different HTTP code.
58
+
59
+ | Code | Description | HTTP code |
60
+ | ---------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | --------- |
61
+ | PARSE_ERROR | Invalid JSON was received by the server, or an error occurred while parsing the request. | 400 |
62
+ | BAD_REQUEST | The server cannot or will not process the request due to something that is perceived to be a client error. | 400 |
63
+ | UNAUTHORIZED | The client request has not been completed because it lacks valid authentication credentials for the requested resource. | 401 |
64
+ | PAYMENT_REQUIRED | The client request requires payment to access the requested resource. | 402 |
65
+ | FORBIDDEN | The client is not authorized to access the requested resource. | 403 |
66
+ | NOT_FOUND | The server cannot find the requested resource. | 404 |
67
+ | METHOD_NOT_SUPPORTED | The server knows the request method, but the target resource doesn't support this method. | 405 |
68
+ | TIMEOUT | The server would like to shut down this unused connection. | 408 |
69
+ | CONFLICT | The request conflicts with the current state of the target resource. | 409 |
70
+ | PRECONDITION_FAILED | Access to the target resource has been denied. | 412 |
71
+ | PAYLOAD_TOO_LARGE | Request entity is larger than limits defined by server. | 413 |
72
+ | UNSUPPORTED_MEDIA_TYPE | The server refuses to accept the request because the payload format is in an unsupported format. | 415 |
73
+ | UNPROCESSABLE_CONTENT | The server understands the request method, and the request entity is correct, but the server was unable to process it. | 422 |
74
+ | 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`.](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/428) | 428 |
75
+ | TOO_MANY_REQUESTS | The rate limit has been exceeded or too many requests are being sent to the server. | 429 |
76
+ | CLIENT_CLOSED_REQUEST | The client closed the connection before the server finished responding. | 499 |
77
+ | INTERNAL_SERVER_ERROR | An unspecified error occurred. | 500 |
78
+ | NOT_IMPLEMENTED | The server does not support the functionality required to fulfill the request. | 501 |
79
+ | BAD_GATEWAY | The server received an invalid response from the upstream server. | 502 |
80
+ | SERVICE_UNAVAILABLE | The server is not ready to handle the request. | 503 |
81
+ | 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 |
82
+
83
+ tRPC exposes a helper function, `getHTTPStatusCodeFromError`, to help you extract the HTTP code from the error:
84
+
85
+ ```ts no-check
86
+ import { getHTTPStatusCodeFromError } from '@trpc/server/http';
87
+
88
+ // Example error you might get if your input validation fails
89
+ const error: TRPCError = {
90
+ name: 'TRPCError',
91
+ code: 'BAD_REQUEST',
92
+ message: '"password" must be at least 4 characters',
93
+ };
70
94
 
71
- function getUserFromDb(id: string) {
72
- if (id === '1') return { id: '1', name: 'Katt' };
73
- return null;
95
+ if (error instanceof TRPCError) {
96
+ const httpCode = getHTTPStatusCodeFromError(error);
97
+ console.log(httpCode); // 400
74
98
  }
75
99
  ```
76
100
 
77
- ### Wrapping original errors with cause
78
-
79
- ```ts
80
- import { TRPCError } from '@trpc/server';
81
- import { publicProcedure, router } from './trpc';
82
-
83
- export const appRouter = router({
84
- riskyOperation: publicProcedure.mutation(async () => {
85
- try {
86
- return await externalService();
87
- } catch (err) {
88
- throw new TRPCError({
89
- code: 'INTERNAL_SERVER_ERROR',
90
- message: 'An unexpected error occurred, please try again later.',
91
- cause: err,
92
- });
93
- }
101
+ > [!TIP]
102
+ >
103
+ > There's a full example of how error handling works in a server-side context in the [Server Side Calls docs](https://trpc.io/docs/server/server-side-calls).
104
+
105
+
106
+ ## Throwing errors
107
+
108
+ tRPC provides an error subclass, `TRPCError`, which you can use to represent an error that occurred inside a procedure.
109
+
110
+ For example, throwing this error:
111
+
112
+ ```ts no-check title="server.ts"
113
+ import { initTRPC, TRPCError } from '@trpc/server';
114
+
115
+ const t = initTRPC.create();
116
+
117
+ const theError = new Error('something went wrong');
118
+
119
+ const appRouter = t.router({
120
+ hello: t.procedure.query(() => {
121
+ throw new TRPCError({
122
+ code: 'INTERNAL_SERVER_ERROR',
123
+ message: 'An unexpected error occurred, please try again later.',
124
+ // optional: pass the original error to retain stack trace
125
+ cause: theError,
126
+ });
94
127
  }),
95
128
  });
96
129
 
97
- async function externalService() {
98
- throw new Error('connection refused');
130
+ // [...]
131
+ ```
132
+
133
+ Results in the following response:
134
+
135
+ ```json
136
+ {
137
+ "id": null,
138
+ "error": {
139
+ "message": "An unexpected error occurred, please try again later.",
140
+ "code": -32603,
141
+ "data": {
142
+ "code": "INTERNAL_SERVER_ERROR",
143
+ "httpStatus": 500,
144
+ "stack": "...",
145
+ "path": "hello"
146
+ }
147
+ }
99
148
  }
100
149
  ```
101
150
 
102
- Pass the original error as `cause` to retain the stack trace for debugging.
151
+ Throw a `TRPCError` with the code that fits, like `NOT_FOUND` or `FORBIDDEN`, so the client gets the right HTTP status. Any other error thrown in a procedure or middleware becomes an `INTERNAL_SERVER_ERROR` with the original error as its `cause`.
152
+
153
+ > [!WARNING]
154
+ > The `message` of an error you didn't throw as a `TRPCError` is still sent to the client, in production too. If your errors may contain internal details, [hide them in your error formatter](https://trpc.io/docs/server/error-formatting#hiding-internal-error-messages).
155
+
156
+
157
+ ## Handling errors
103
158
 
104
- ### Global error handling with onError
159
+ All errors that occur in a procedure go through the `onError` method before being sent to the client. Here you can handle errors (To change errors see [error formatting](https://trpc.io/docs/server/error-formatting)).
105
160
 
106
- ```ts
161
+ ```ts no-check title="server.ts"
107
162
  import { createHTTPServer } from '@trpc/server/adapters/standalone';
108
- import { appRouter } from './appRouter';
163
+ import { appRouter } from './router';
109
164
 
110
165
  const server = createHTTPServer({
111
166
  router: appRouter,
@@ -113,141 +168,192 @@ const server = createHTTPServer({
113
168
  const { error, type, path, input, ctx, req } = opts;
114
169
  console.error('Error:', error);
115
170
  if (error.code === 'INTERNAL_SERVER_ERROR') {
116
- // send to bug reporting service
171
+ // send to bug reporting
117
172
  }
118
173
  },
119
174
  });
120
-
121
- server.listen(3000);
122
175
  ```
123
176
 
124
- ### Extracting HTTP status from TRPCError
125
-
126
- ```ts
127
- import { TRPCError } from '@trpc/server';
128
- import { getHTTPStatusCodeFromError } from '@trpc/server/http';
177
+ The `onError` parameter is an object that contains all information about the error and the context it occurs in:
129
178
 
130
- function handleError(error: unknown) {
131
- if (error instanceof TRPCError) {
132
- const httpCode = getHTTPStatusCodeFromError(error);
133
- console.log(httpCode); // e.g., 400, 401, 404, 500
134
- }
179
+ ```ts no-check
180
+ interface OnErrorOpts {
181
+ error: TRPCError;
182
+ type: 'query' | 'mutation' | 'subscription' | 'unknown';
183
+ path: string | undefined;
184
+ input: unknown;
185
+ ctx: unknown;
186
+ req: Request;
135
187
  }
136
188
  ```
137
189
 
138
- ## Common Mistakes
190
+ ## Error Formatting
139
191
 
140
- ### [HIGH] Throwing plain Error instead of TRPCError
192
+ From https://trpc.io/docs/server/error-formatting
141
193
 
142
- Wrong:
194
+ The error formatting in your router will be inferred all the way to your client.
143
195
 
144
- ```ts
145
- import { publicProcedure } from './trpc';
196
+ ### Usage example highlighted
146
197
 
147
- const proc = publicProcedure.query(() => {
148
- throw new Error('Not found');
149
- // client receives 500 INTERNAL_SERVER_ERROR
150
- });
151
- ```
198
+ #### Adding custom formatting
152
199
 
153
- Correct:
154
-
155
- ```ts
156
- import { TRPCError } from '@trpc/server';
157
- import { publicProcedure } from './trpc';
200
+ ```ts no-check title="server.ts"
201
+ import { initTRPC } from '@trpc/server';
202
+ import { ZodError } from 'zod';
158
203
 
159
- const proc = publicProcedure.query(() => {
160
- throw new TRPCError({
161
- code: 'NOT_FOUND',
162
- message: 'User not found',
163
- });
164
- // client receives 404 NOT_FOUND
204
+ export const t = initTRPC.create({
205
+ errorFormatter(opts) {
206
+ const { shape, error } = opts;
207
+ return {
208
+ ...shape,
209
+ data: {
210
+ ...shape.data,
211
+ zodError:
212
+ error.code === 'BAD_REQUEST' && error.cause instanceof ZodError
213
+ ? error.cause.flatten()
214
+ : null,
215
+ },
216
+ };
217
+ },
165
218
  });
166
219
  ```
167
220
 
168
- Plain Error objects are caught and wrapped as INTERNAL_SERVER_ERROR (500); use TRPCError with a specific code for proper HTTP status mapping.
169
-
170
- Source: www/docs/server/error-handling.md
221
+ #### Usage in React
171
222
 
172
- ### [MEDIUM] Expecting stack traces in production
223
+ ```tsx no-check title="components/MyComponent.tsx"
224
+ import { useEffect } from 'react';
225
+ import { trpc } from '../utils/trpc';
173
226
 
174
- Wrong:
227
+ export function MyComponent() {
228
+ const mutation = trpc.addPost.useMutation();
175
229
 
176
- ```ts
177
- import { initTRPC } from '@trpc/server';
230
+ useEffect(() => {
231
+ mutation.mutate({ title: 'example' });
232
+ }, []);
178
233
 
179
- // No explicit isDev setting
180
- const t = initTRPC.create();
181
- // Stack traces may or may not appear depending on NODE_ENV
234
+ if (mutation.error?.data?.zodError) {
235
+ // zodError will be inferred
236
+ return (
237
+ <pre>Error: {JSON.stringify(mutation.error.data.zodError, null, 2)}</pre>
238
+ );
239
+ }
240
+ return <>[...]</>;
241
+ }
182
242
  ```
183
243
 
184
- Correct:
244
+ ### Hiding internal error messages
245
+
246
+ The default shape includes the error's `message`, even for unexpected errors such as a failed database query. To keep those details out of production responses, replace the message of `INTERNAL_SERVER_ERROR`s:
185
247
 
186
- ```ts
248
+ ```ts no-check title="server.ts"
187
249
  import { initTRPC } from '@trpc/server';
188
250
 
189
- const t = initTRPC.create({
190
- isDev: process.env.NODE_ENV === 'development',
251
+ export const t = initTRPC.create({
252
+ errorFormatter(opts) {
253
+ const { shape, error } = opts;
254
+ if (
255
+ error.code === 'INTERNAL_SERVER_ERROR' &&
256
+ process.env.NODE_ENV === 'production'
257
+ ) {
258
+ return { ...shape, message: 'Internal server error' };
259
+ }
260
+ return shape;
261
+ },
191
262
  });
192
263
  ```
193
264
 
194
- Stack traces are included only when `isDev` is true (default: `NODE_ENV !== "production"`); set `isDev` explicitly for deterministic behavior across runtimes.
265
+ The full error, with its `cause`, still reaches your [`onError`](https://trpc.io/docs/server/error-handling#handling-errors) handler.
195
266
 
196
- Source: www/docs/server/error-handling.md
267
+ ### Per-procedure error formatting
197
268
 
198
- ### [HIGH] Not handling Zod errors in errorFormatter
269
+ Errors can be formatted on a per-procedure basis using the `.errors()` method, which can be chained to produce a union of possible error shapes for each procedure.
199
270
 
200
- Wrong:
271
+ When a middleware or procedure throws an error, it bubbles upward through all `.errors()` handlers until one returns a shape or the global errorFormatter is reached.
201
272
 
202
- ```ts
203
- import { initTRPC } from '@trpc/server';
273
+ ```ts no-check title="server.ts"
274
+ const rateLimitedProcedure = t.procedure
275
+ .errors((opts) => {
276
+ if (opts.error.cause instanceof RateLimitError) {
277
+ return {
278
+ ...opts.shape,
279
+ data: { ...opts.shape.data, kind: 'RATE_LIMIT' as const },
280
+ };
281
+ }
282
+ return undefined;
283
+ })
284
+ .use(opts => {
285
+ // Important: errors bubble up so a throwing middleware must come after the .errors() handler
286
+ if (isRateLimited(opts)) {
287
+ throw new RateLimitError();
288
+ }
204
289
 
205
- // No errorFormatter -- client gets generic "Input validation failed"
206
- const t = initTRPC.create();
207
- ```
290
+ return opts.next();
291
+ });
208
292
 
209
- Correct:
293
+ const billedProcedure = rateLimitedProcedure
294
+ .errors((opts) => {
295
+ if (opts.error.cause instanceof PaymentRequiredError) {
296
+ return {
297
+ ...opts.shape,
298
+ data: {
299
+ ...opts.shape.data,
300
+ kind: 'PAYMENT_REQUIRED' as const,
301
+ amountDue: opts.error.cause.amountDue,
302
+ },
303
+ };
304
+ }
305
+ return undefined;
306
+ });
210
307
 
211
- ```ts
212
- import { initTRPC } from '@trpc/server';
213
- import { ZodError } from 'zod';
308
+ const addPostProcedure = billedProcedure.mutation(opts => {
309
+ if (isPaymentRequired(opts)) {
310
+ throw new PaymentRequiredError(100);
311
+ }
214
312
 
215
- const t = initTRPC.create({
216
- errorFormatter({ shape, error }) {
217
- return {
218
- ...shape,
219
- data: {
220
- ...shape.data,
221
- zodError:
222
- error.code === 'BAD_REQUEST' && error.cause instanceof ZodError
223
- ? error.cause.flatten()
224
- : null,
225
- },
226
- };
227
- },
313
+ return {
314
+ success: true,
315
+ };
228
316
  });
229
317
  ```
230
318
 
231
- Without a custom errorFormatter, the client receives a generic message without field-level validation details from Zod.
319
+ ### All properties sent to `errorFormatter()`
232
320
 
233
- Source: www/docs/server/error-formatting.md
321
+ > tRPC is compliant with [JSON-RPC 2.0](https://www.jsonrpc.org/specification)
234
322
 
235
- ## Error Code Reference
323
+ ```ts no-check
324
+ interface ErrorFormatterOpts {
325
+ error: TRPCError;
326
+ type: 'query' | 'mutation' | 'subscription' | 'unknown';
327
+ path: string | undefined;
328
+ input: unknown;
329
+ ctx: unknown;
330
+ shape: { message: string; code: number; data: unknown };
331
+ }
332
+ ```
236
333
 
237
- | Code | HTTP | Use when |
238
- | --------------------- | ---- | ------------------------------------ |
239
- | BAD_REQUEST | 400 | Invalid input |
240
- | UNAUTHORIZED | 401 | Missing or invalid auth credentials |
241
- | FORBIDDEN | 403 | Authenticated but not authorized |
242
- | NOT_FOUND | 404 | Resource does not exist |
243
- | CONFLICT | 409 | Request conflicts with current state |
244
- | UNPROCESSABLE_CONTENT | 422 | Valid syntax but semantic error |
245
- | TOO_MANY_REQUESTS | 429 | Rate limit exceeded |
246
- | INTERNAL_SERVER_ERROR | 500 | Unexpected server error |
334
+ **`DefaultErrorShape`:**
335
+
336
+ ```ts no-check
337
+ type DefaultErrorData = {
338
+ code: TRPC_ERROR_CODE_KEY;
339
+ httpStatus: number;
340
+ /**
341
+ * Path to the procedure that threw the error
342
+ */
343
+ path?: string;
344
+ /**
345
+ * Stack trace of the error (only in development)
346
+ */
347
+ stack?: string;
348
+ };
349
+
350
+ interface DefaultErrorShape {
351
+ message: string;
352
+ code: TRPC_ERROR_CODE_NUMBER;
353
+ data: DefaultErrorData;
354
+ }
355
+ ```
247
356
 
248
- ## See Also
357
+ ## Related skills
249
358
 
250
- - `server-setup` -- initTRPC configuration including isDev
251
- - `validators` -- input validation that triggers BAD_REQUEST errors
252
- - `middlewares` -- auth middleware throwing UNAUTHORIZED
253
- - `server-side-calls` -- catching TRPCError in server-side callers
359
+ - `server-setup` (https://trpc.io/docs/server/overview): `npx @tanstack/intent@latest load @trpc/server#server-setup`