@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.
- package/README.md +0 -8
- package/dist/adapters/aws-lambda/index.cjs +1 -1
- package/dist/adapters/aws-lambda/index.d.cts.map +1 -1
- package/dist/adapters/aws-lambda/index.d.mts.map +1 -1
- package/dist/adapters/aws-lambda/index.mjs +1 -1
- package/dist/adapters/aws-lambda/index.mjs.map +1 -1
- package/dist/adapters/express.cjs +1 -1
- package/dist/adapters/express.mjs +1 -1
- package/dist/adapters/express.mjs.map +1 -1
- package/dist/adapters/fastify/index.cjs +3 -3
- package/dist/adapters/fastify/index.mjs +3 -3
- package/dist/adapters/fetch/index.cjs +1 -1
- package/dist/adapters/fetch/index.mjs +1 -1
- package/dist/adapters/next-app-dir.mjs.map +1 -1
- package/dist/adapters/next.cjs +1 -1
- package/dist/adapters/next.mjs +1 -1
- package/dist/adapters/next.mjs.map +1 -1
- package/dist/adapters/node-http/index.cjs +1 -1
- package/dist/adapters/node-http/index.mjs +1 -1
- package/dist/adapters/standalone.cjs +9 -3
- package/dist/adapters/standalone.d.cts +0 -1
- package/dist/adapters/standalone.d.cts.map +1 -1
- package/dist/adapters/standalone.d.mts +0 -1
- package/dist/adapters/standalone.d.mts.map +1 -1
- package/dist/adapters/standalone.mjs +9 -3
- package/dist/adapters/standalone.mjs.map +1 -1
- package/dist/adapters/ws.cjs +1 -1
- package/dist/adapters/ws.mjs +1 -1
- package/dist/asyncGeneratorDelegate-FcEJT04i.mjs.map +1 -1
- package/dist/codes-C9N0z0an.mjs.map +1 -1
- package/dist/getErrorShape-zlj81BiC.mjs.map +1 -1
- package/dist/http.cjs +1 -1
- package/dist/http.mjs +1 -1
- package/dist/initTRPC-RMeQIy9H.mjs.map +1 -1
- package/dist/{node-http-B5jkpWn7.mjs → node-http-ChhZEv1k.mjs} +2 -2
- package/dist/node-http-ChhZEv1k.mjs.map +1 -0
- package/dist/{node-http-BZ0HlzkC.cjs → node-http-X8RiQEuH.cjs} +1 -1
- package/dist/parseTRPCMessage-CJ4DJVBp.mjs.map +1 -1
- package/dist/{resolveResponse-b9D_SrLs.cjs → resolveResponse-CoGjFxK0.cjs} +8 -4
- package/dist/{resolveResponse-DH5L33sC.mjs → resolveResponse-DksrxZ2k.mjs} +9 -5
- package/dist/resolveResponse-DksrxZ2k.mjs.map +1 -0
- package/dist/unstable-core-do-not-import-B8epiErP.d.cts.map +1 -1
- package/dist/unstable-core-do-not-import-Dbo98mkh.d.mts.map +1 -1
- package/dist/unstable-core-do-not-import.cjs +1 -1
- package/dist/unstable-core-do-not-import.mjs +1 -1
- package/dist/unstable-core-do-not-import.mjs.map +1 -1
- package/dist/{ws-83TNWW-W.cjs → ws-7qWW7Uec.cjs} +2 -2
- package/dist/{ws-DJ2SSChC.mjs → ws-BYfo-HED.mjs} +3 -3
- package/dist/ws-BYfo-HED.mjs.map +1 -0
- package/package.json +9 -12
- package/skills/adapter-aws-lambda/SKILL.md +152 -134
- package/skills/adapter-express/SKILL.md +127 -113
- package/skills/adapter-fastify/SKILL.md +228 -136
- package/skills/adapter-fetch/SKILL.md +388 -111
- package/skills/adapter-standalone/SKILL.md +184 -94
- package/skills/auth/SKILL.md +327 -202
- package/skills/auth/references/client-cors.md +29 -0
- package/skills/caching/SKILL.md +58 -148
- package/skills/error-handling/SKILL.md +280 -174
- package/skills/middlewares/SKILL.md +320 -121
- package/skills/non-json-content-types/SKILL.md +149 -168
- package/skills/server-setup/SKILL.md +355 -253
- package/skills/server-setup/references/server-context.md +219 -0
- package/skills/server-setup/references/server-merging-routers.md +141 -0
- package/skills/server-setup/references/server-metadata.md +105 -0
- package/skills/server-setup/references/server-procedures.md +172 -0
- package/skills/server-setup/references/server-routers.md +123 -0
- package/skills/server-side-calls/SKILL.md +247 -152
- package/skills/service-oriented-architecture/SKILL.md +81 -177
- package/skills/subscriptions/SKILL.md +341 -297
- package/skills/subscriptions/references/client-links-httpSubscriptionLink.md +404 -0
- package/skills/subscriptions/references/client-links-wsLink.md +122 -0
- package/skills/subscriptions/references/server-websockets.md +297 -0
- package/skills/trpc-router/SKILL.md +156 -86
- package/skills/validators/SKILL.md +384 -128
- package/src/adapters/aws-lambda/getPlanner.ts +4 -3
- package/src/adapters/aws-lambda/index.ts +2 -1
- package/src/adapters/express.ts +1 -1
- package/src/adapters/next-app-dir/nextAppDirCaller.ts +4 -4
- package/src/adapters/next-app-dir/rethrowNextErrors.ts +1 -1
- package/src/adapters/next.ts +1 -1
- package/src/adapters/node-http/incomingMessageToRequest.ts +1 -1
- package/src/adapters/node-http/nodeHTTPRequestHandler.ts +1 -1
- package/src/adapters/node-http/types.ts +1 -1
- package/src/adapters/node-http/writeResponse.ts +1 -1
- package/src/adapters/standalone.ts +12 -6
- package/src/adapters/ws.ts +5 -5
- package/src/unstable-core-do-not-import/clientish/inferrable.ts +4 -1
- package/src/unstable-core-do-not-import/clientish/serialize.ts +4 -4
- package/src/unstable-core-do-not-import/error/TRPCError.ts +3 -3
- package/src/unstable-core-do-not-import/http/formDataToObject.ts +1 -1
- package/src/unstable-core-do-not-import/http/getHTTPStatusCode.ts +1 -1
- package/src/unstable-core-do-not-import/http/resolveResponse.ts +13 -2
- package/src/unstable-core-do-not-import/procedure.ts +5 -2
- package/src/unstable-core-do-not-import/procedureBuilder.ts +3 -2
- package/src/unstable-core-do-not-import/rootConfig.ts +2 -2
- package/src/unstable-core-do-not-import/router.ts +5 -2
- package/src/unstable-core-do-not-import/rpc/envelopes.ts +3 -2
- package/src/unstable-core-do-not-import/stream/jsonl.ts +2 -1
- package/src/unstable-core-do-not-import/stream/sse.types.ts +1 -1
- package/src/unstable-core-do-not-import/stream/utils/asyncIterable.ts +1 -1
- package/src/unstable-core-do-not-import/stream/utils/createDeferred.ts +1 -1
- package/src/unstable-core-do-not-import/stream/utils/disposable.ts +6 -6
- package/src/unstable-core-do-not-import/stream/utils/mergeAsyncIterables.ts +2 -2
- package/src/unstable-core-do-not-import/stream/utils/withPing.ts +3 -1
- package/src/unstable-core-do-not-import/transformer.ts +4 -1
- package/src/unstable-core-do-not-import/types.ts +3 -2
- package/src/unstable-core-do-not-import/utils.ts +1 -1
- package/src/vendor/standard-schema-v1/spec.ts +2 -2
- package/src/vendor/unpromise/unpromise.ts +1 -1
- package/bin/intent.js +0 -20
- package/dist/node-http-B5jkpWn7.mjs.map +0 -1
- package/dist/resolveResponse-DH5L33sC.mjs.map +0 -1
- 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
|
-
-
|
|
15
|
-
-
|
|
16
|
-
|
|
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
|
-
|
|
15
|
+
<!-- Generated from www/v11/docs/server/error-handling.md by www/build/skills.ts. Edit the docs instead. -->
|
|
20
16
|
|
|
21
|
-
|
|
17
|
+
# Error Handling
|
|
22
18
|
|
|
23
|
-
|
|
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
|
-
|
|
29
|
-
|
|
30
|
-
|
|
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
|
-
|
|
44
|
-
|
|
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
|
-
##
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
import {
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
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
|
-
|
|
72
|
-
|
|
73
|
-
|
|
95
|
+
if (error instanceof TRPCError) {
|
|
96
|
+
const httpCode = getHTTPStatusCodeFromError(error);
|
|
97
|
+
console.log(httpCode); // 400
|
|
74
98
|
}
|
|
75
99
|
```
|
|
76
100
|
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
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
|
-
|
|
98
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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 './
|
|
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
|
|
171
|
+
// send to bug reporting
|
|
117
172
|
}
|
|
118
173
|
},
|
|
119
174
|
});
|
|
120
|
-
|
|
121
|
-
server.listen(3000);
|
|
122
175
|
```
|
|
123
176
|
|
|
124
|
-
|
|
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
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
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
|
-
##
|
|
190
|
+
## Error Formatting
|
|
139
191
|
|
|
140
|
-
|
|
192
|
+
From https://trpc.io/docs/server/error-formatting
|
|
141
193
|
|
|
142
|
-
|
|
194
|
+
The error formatting in your router will be inferred all the way to your client.
|
|
143
195
|
|
|
144
|
-
|
|
145
|
-
import { publicProcedure } from './trpc';
|
|
196
|
+
### Usage example highlighted
|
|
146
197
|
|
|
147
|
-
|
|
148
|
-
throw new Error('Not found');
|
|
149
|
-
// client receives 500 INTERNAL_SERVER_ERROR
|
|
150
|
-
});
|
|
151
|
-
```
|
|
198
|
+
#### Adding custom formatting
|
|
152
199
|
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
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
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
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
|
-
|
|
169
|
-
|
|
170
|
-
Source: www/docs/server/error-handling.md
|
|
221
|
+
#### Usage in React
|
|
171
222
|
|
|
172
|
-
|
|
223
|
+
```tsx no-check title="components/MyComponent.tsx"
|
|
224
|
+
import { useEffect } from 'react';
|
|
225
|
+
import { trpc } from '../utils/trpc';
|
|
173
226
|
|
|
174
|
-
|
|
227
|
+
export function MyComponent() {
|
|
228
|
+
const mutation = trpc.addPost.useMutation();
|
|
175
229
|
|
|
176
|
-
|
|
177
|
-
|
|
230
|
+
useEffect(() => {
|
|
231
|
+
mutation.mutate({ title: 'example' });
|
|
232
|
+
}, []);
|
|
178
233
|
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
265
|
+
The full error, with its `cause`, still reaches your [`onError`](https://trpc.io/docs/server/error-handling#handling-errors) handler.
|
|
195
266
|
|
|
196
|
-
|
|
267
|
+
### Per-procedure error formatting
|
|
197
268
|
|
|
198
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
206
|
-
|
|
207
|
-
```
|
|
290
|
+
return opts.next();
|
|
291
|
+
});
|
|
208
292
|
|
|
209
|
-
|
|
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
|
-
|
|
212
|
-
|
|
213
|
-
|
|
308
|
+
const addPostProcedure = billedProcedure.mutation(opts => {
|
|
309
|
+
if (isPaymentRequired(opts)) {
|
|
310
|
+
throw new PaymentRequiredError(100);
|
|
311
|
+
}
|
|
214
312
|
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
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
|
-
|
|
319
|
+
### All properties sent to `errorFormatter()`
|
|
232
320
|
|
|
233
|
-
|
|
321
|
+
> tRPC is compliant with [JSON-RPC 2.0](https://www.jsonrpc.org/specification)
|
|
234
322
|
|
|
235
|
-
|
|
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
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
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
|
-
##
|
|
357
|
+
## Related skills
|
|
249
358
|
|
|
250
|
-
- `server-setup`
|
|
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`
|