faultferry 0.0.0-stage → 0.1.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/LICENSE +21 -0
- package/README.es.md +220 -0
- package/README.ja.md +220 -0
- package/README.md +219 -2
- package/README.pt.md +220 -0
- package/dist/index.cjs +875 -0
- package/dist/index.d.cts +121 -0
- package/index.d.ts +121 -0
- package/package.json +65 -4
- package/src/index.js +868 -0
package/README.md
CHANGED
|
@@ -1,3 +1,220 @@
|
|
|
1
|
-
|
|
1
|
+
<picture>
|
|
2
|
+
<source media="(prefers-color-scheme: dark)" srcset="assets/banner-dark.svg">
|
|
3
|
+
<img alt="faultferry: send errors across processes and bring them back whole" src="assets/banner-light.svg" width="100%">
|
|
4
|
+
</picture>
|
|
2
5
|
|
|
3
|
-
|
|
6
|
+
**English** | [Português (Brasil)](README.pt.md) | [Español](README.es.md) | [日本語](README.ja.md)
|
|
7
|
+
|
|
8
|
+
[](https://github.com/kwy404/faultferry/actions/workflows/ci.yml)
|
|
9
|
+
[](https://www.npmjs.com/package/faultferry)
|
|
10
|
+
[](#size)
|
|
11
|
+
[](package.json)
|
|
12
|
+
[](index.d.ts)
|
|
13
|
+
[](LICENSE)
|
|
14
|
+
|
|
15
|
+
**Serialize JavaScript errors to plain JSON and deserialize them back, exactly.** faultferry keeps the class, message, stack, cause chain (with cycles), AggregateError, SuppressedError, DOMException, custom error classes and thrown non errors, so you can send errors across processes and bring them back whole.
|
|
16
|
+
|
|
17
|
+
`JSON.stringify(new Error('boom'))` gives you `{}`. Workers, child processes, HTTP and message queues move data, not errors, so the class, the cause chain and every custom field get lost on the way. faultferry turns any thrown value into plain JSON and rebuilds it on the other side: same class, message, stack, cause chain (cycles included), AggregateError members, SuppressedError fields, DOMException name and code, and own properties. It never throws on hostile input and has zero dependencies.
|
|
18
|
+
|
|
19
|
+
Website and live playground: https://kwy404.github.io/faultferry/
|
|
20
|
+
|
|
21
|
+
## Install
|
|
22
|
+
|
|
23
|
+
```sh
|
|
24
|
+
npm i faultferry
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
ESM and CommonJS builds, hand written TypeScript types, Node.js 18 or newer, Bun, Deno and modern browsers.
|
|
28
|
+
|
|
29
|
+
## Quick start
|
|
30
|
+
|
|
31
|
+
```js
|
|
32
|
+
import { serialize, deserialize, register } from 'faultferry';
|
|
33
|
+
|
|
34
|
+
class HttpError extends Error {
|
|
35
|
+
constructor(message, status, options) {
|
|
36
|
+
super(message, options);
|
|
37
|
+
this.name = 'HttpError';
|
|
38
|
+
this.status = status;
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
register(HttpError); // on both sides
|
|
42
|
+
|
|
43
|
+
const error = new HttpError('checkout failed', 502, { cause: new TypeError('fetch failed') });
|
|
44
|
+
|
|
45
|
+
const wire = JSON.stringify(serialize(error));
|
|
46
|
+
const back = deserialize(JSON.parse(wire));
|
|
47
|
+
|
|
48
|
+
back instanceof HttpError; // true
|
|
49
|
+
back.status; // 502
|
|
50
|
+
back.cause instanceof TypeError; // true
|
|
51
|
+
back.stack === error.stack; // true
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
Across a worker:
|
|
55
|
+
|
|
56
|
+
```js
|
|
57
|
+
// worker.js
|
|
58
|
+
self.onmessage = async ({ data }) => {
|
|
59
|
+
try {
|
|
60
|
+
postMessage({ ok: true, value: await run(data) });
|
|
61
|
+
} catch (error) {
|
|
62
|
+
postMessage({ ok: false, error: serialize(error) });
|
|
63
|
+
}
|
|
64
|
+
};
|
|
65
|
+
|
|
66
|
+
// main.js
|
|
67
|
+
worker.onmessage = ({ data }) => {
|
|
68
|
+
if (!data.ok) throw deserialize(data.error);
|
|
69
|
+
};
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
From a server to a browser, without leaking stack traces:
|
|
73
|
+
|
|
74
|
+
```js
|
|
75
|
+
app.use((error, req, res, next) => {
|
|
76
|
+
res.status(error.status ?? 500).json(serialize(error, { stack: false, maxDepth: 8 }));
|
|
77
|
+
});
|
|
78
|
+
```
|
|
79
|
+
|
|
80
|
+
## API
|
|
81
|
+
|
|
82
|
+
### `serialize(value, options?)`
|
|
83
|
+
|
|
84
|
+
Converts any value, usually something that was thrown, into a plain value that `JSON.stringify`, `postMessage` and `structuredClone` accept. Never throws on hostile input.
|
|
85
|
+
|
|
86
|
+
| option | default | meaning |
|
|
87
|
+
| --- | --- | --- |
|
|
88
|
+
| `maxDepth` | `32` | Nesting limit. Deeper containers become `"[Object]"`, `"[Array]"`, `"[Map]"` or `"[Set]"`; deeper errors keep only class, name and message. |
|
|
89
|
+
| `maxNodes` | `10000` | Total containers and errors copied before the same truncation applies. |
|
|
90
|
+
| `maxLength` | `Infinity` | Longest string kept. Longer strings are cut and end with `...`. |
|
|
91
|
+
| `maxItems` | `Infinity` | Most array items, object keys and Map or Set entries copied per container. |
|
|
92
|
+
| `stack` | `true` | Include stack traces. Pass `false` before sending errors to untrusted clients. |
|
|
93
|
+
| `toJSON` | `true` | Honor `toJSON()` methods. On an error, the returned object replaces the own enumerable properties. |
|
|
94
|
+
| `classes` | `[]` | Extra error classes recognized for this call only. |
|
|
95
|
+
|
|
96
|
+
A negative or non numeric limit throws a `RangeError`; anything in `classes` that is not a named class throws a `TypeError`. Those are programming mistakes, not input problems.
|
|
97
|
+
|
|
98
|
+
### `deserialize(data, options?)`
|
|
99
|
+
|
|
100
|
+
Rebuilds a value produced by `serialize()`. Errors come back as real error objects with the right prototype. Constructors are never called, so required constructor arguments do not matter. Unknown classes come back as the closest known class (usually `Error`) with the original `name`. Never throws on hostile input.
|
|
101
|
+
|
|
102
|
+
| option | default | meaning |
|
|
103
|
+
| --- | --- | --- |
|
|
104
|
+
| `maxDepth` | `256` | Nesting limit. Deeper values become `undefined`. Keep it at least as high as the serializer's `maxDepth`. |
|
|
105
|
+
| `classes` | `[]` | Extra error classes recognized for this call only. |
|
|
106
|
+
|
|
107
|
+
### `register(ErrorClass, name?)`
|
|
108
|
+
|
|
109
|
+
Registers a custom error class under `name` (default: the class name) so `deserialize()` can rebuild its instances. Returns the class. Register the same classes on both sides. Built in errors are always known: `Error`, `TypeError`, `RangeError`, `ReferenceError`, `SyntaxError`, `EvalError`, `URIError`, `AggregateError`, `SuppressedError` (where it exists) and `DOMException`.
|
|
110
|
+
|
|
111
|
+
### `unregister(classOrName)`
|
|
112
|
+
|
|
113
|
+
Removes a registered class, by class or by name. Returns `true` when something was removed.
|
|
114
|
+
|
|
115
|
+
### `isError(value)`
|
|
116
|
+
|
|
117
|
+
`true` for real error objects, the ones with the internal `[[ErrorData]]` slot, including errors from other realms such as `node:vm` contexts and iframes. It uses the native [`Error.isError`](https://tc39.es/proposal-is-error/) when the runtime has it. The fallback checks `Object.prototype.toString` when the value has no own string `Symbol.toStringTag`, and otherwise asks `structuredClone`, which only clones real errors as errors. Objects that merely inherit from `Error.prototype` are not errors.
|
|
118
|
+
|
|
119
|
+
## The wire format
|
|
120
|
+
|
|
121
|
+
An error becomes an object with `$error` (the registry key), `name`, `message`, `stack` and only the fields it actually had:
|
|
122
|
+
|
|
123
|
+
```json
|
|
124
|
+
{
|
|
125
|
+
"$error": "HttpError",
|
|
126
|
+
"name": "HttpError",
|
|
127
|
+
"message": "checkout failed",
|
|
128
|
+
"stack": "HttpError: checkout failed\n at ...",
|
|
129
|
+
"cause": { "$error": "TypeError", "name": "TypeError", "message": "fetch failed", "stack": "..." },
|
|
130
|
+
"props": { "name": "HttpError", "status": 502 }
|
|
131
|
+
}
|
|
132
|
+
```
|
|
133
|
+
|
|
134
|
+
- `cause`, `errors` (AggregateError), `error` and `suppressed` (SuppressedError) are written only when they are own properties of the error.
|
|
135
|
+
- `props` holds the own enumerable properties, or the result of `toJSON()`.
|
|
136
|
+
- `code` is written for DOMException for readability; the name decides the code on the way back.
|
|
137
|
+
- Values JSON cannot represent become small records: `{ "$value": "undefined" }`, `NaN`, `Infinity`, `-Infinity`, `-0`, `bigint`, `Date`, `RegExp`, `Map` and `Set`.
|
|
138
|
+
- Cycles and shared references become `{ "$ref": n }`, where `n` is the position of the target container in a depth first walk. They come back with the same identity.
|
|
139
|
+
- A plain object whose keys collide with these tags is wrapped in `{ "$escape": ... }`, so data never turns into an error by accident.
|
|
140
|
+
- Functions become `"[Function: name]"` and symbols become `"Symbol(description)"`.
|
|
141
|
+
|
|
142
|
+
## Behavior notes
|
|
143
|
+
|
|
144
|
+
- Own enumerable properties come back enumerable; `message`, `stack`, `cause`, `errors`, `error` and `suppressed` come back non enumerable, as the language creates them ([ECMA-262 InstallErrorCause](https://tc39.es/ecma262/#sec-installerrorcause), [AggregateError](https://tc39.es/ecma262/#sec-aggregate-error-objects)).
|
|
145
|
+
- An error that never had a stack comes back without one; the restored error never gets a fresh stack from the place where `deserialize` ran.
|
|
146
|
+
- Throwing getters, revoked proxies and prototype traps are skipped, never followed by an exception. A `message` getter that throws becomes a missing message.
|
|
147
|
+
- `__proto__` keys are stored and restored as plain data with `Object.defineProperty`, so they cannot change a prototype.
|
|
148
|
+
- A thrown string comes back as the same string. Nothing is wrapped in a fake error.
|
|
149
|
+
|
|
150
|
+
## Compared with structuredClone
|
|
151
|
+
|
|
152
|
+
Checked on Node 24 by `test/structured-clone.test.js`.
|
|
153
|
+
|
|
154
|
+
| After a round trip | faultferry | structuredClone |
|
|
155
|
+
| --- | --- | --- |
|
|
156
|
+
| Output | JSON safe value, any transport | Only structured clone channels, no text |
|
|
157
|
+
| Custom class instance | Same class (registered) | Plain `Error` |
|
|
158
|
+
| AggregateError `errors` | Kept | Lost, comes back as `Error` |
|
|
159
|
+
| SuppressedError | Kept | Lost |
|
|
160
|
+
| Own properties (`status`, `code`) | Kept | Dropped |
|
|
161
|
+
| Circular cause | Kept | Kept |
|
|
162
|
+
| DOMException name and code | Kept | Kept |
|
|
163
|
+
| Function in a cause or prop | Becomes `"[Function: name]"` | Throws `DataCloneError` |
|
|
164
|
+
| Proxy anywhere in the graph | Read safely or skipped | Throws `DataCloneError` |
|
|
165
|
+
| `message` getter that throws | Skipped | Throws |
|
|
166
|
+
|
|
167
|
+
## Why not serialize-error?
|
|
168
|
+
|
|
169
|
+
serialize-error is the long standing package for this job. faultferry makes different choices, all checked against serialize-error 13.1.0 on Node 24 in a scratch folder:
|
|
170
|
+
|
|
171
|
+
- A circular cause becomes the string `"[Circular]"` there; here it is restored as the same object.
|
|
172
|
+
- Shared references are duplicated there; here they keep their identity.
|
|
173
|
+
- DOMException comes back as a plain Error with `name` and `code` there; here it is a DOMException.
|
|
174
|
+
- SuppressedError `error` and `suppressed` are lost there; here they are kept.
|
|
175
|
+
- Thrown strings are wrapped in `NonError` there; here they stay strings. `undefined` is dropped, `NaN` becomes `null`, BigInt becomes `"10n"` and Date becomes a string there; here they come back as the same values.
|
|
176
|
+
- An own property getter that throws, or a revoked proxy, makes serialize-error throw; faultferry never throws on input.
|
|
177
|
+
- Custom classes need `addKnownErrorConstructor` there and `register` here; both work.
|
|
178
|
+
|
|
179
|
+
serialize-error has a much larger user base and a longer track record. If its output format already fits your system, it is a fine choice.
|
|
180
|
+
|
|
181
|
+
## Benchmarks
|
|
182
|
+
|
|
183
|
+
`npm run bench`, operations per second, median of five runs, higher is better. Node 24.16.0, AMD Ryzen 7 7800X3D, Windows x64, 2026-12-04.
|
|
184
|
+
|
|
185
|
+
| case | faultferry serialize | serialize-error serialize | faultferry deserialize | serialize-error deserialize | structuredClone (no JSON) |
|
|
186
|
+
| --- | ---: | ---: | ---: | ---: | ---: |
|
|
187
|
+
| simple TypeError | 1.65M | 893k | 548k | 143k | 697k |
|
|
188
|
+
| cause chain x6 | 319k | 160k | 98k | 10k | 193k |
|
|
189
|
+
| error with props | 821k | 426k | 313k | 121k | 757k |
|
|
190
|
+
| AggregateError x20 | 68k | 40k | 22k | 3k | 638k |
|
|
191
|
+
|
|
192
|
+
Serialize includes `JSON.stringify`; deserialize includes `JSON.parse`. structuredClone produces no JSON and drops the AggregateError members, which is why it is so fast in that case. serialize-error is installed only for the benchmark and is not a dependency.
|
|
193
|
+
|
|
194
|
+
## Size
|
|
195
|
+
|
|
196
|
+
4.7 kB gzip with comments and whitespace stripped (7.0 kB gzip as published, with JSDoc). `npm run size` prints the numbers. Zero runtime dependencies, `sideEffects: false`.
|
|
197
|
+
|
|
198
|
+
## Compatibility
|
|
199
|
+
|
|
200
|
+
Node.js 18 or newer (tested on 18, 20, 22 and 24 in CI, on Linux, Windows and macOS), Bun and Deno (smoke tests in CI), modern browsers, Web Workers and Service Workers. `SuppressedError` support turns on where the runtime has it.
|
|
201
|
+
|
|
202
|
+
## FAQ
|
|
203
|
+
|
|
204
|
+
**Why does `JSON.stringify(error)` return `{}`?** `message`, `stack` and `cause` are own properties that are not enumerable, and `JSON.stringify` only writes enumerable ones. `serialize(error)` copies those fields into a plain object first, and `deserialize` turns that object back into a real error.
|
|
205
|
+
|
|
206
|
+
**Is it safe to deserialize data from the network?** `deserialize` never calls constructors or getters from the data, never changes prototypes and treats `__proto__` keys as plain data. It only builds classes you registered. Pass `stack: false` when you serialize for untrusted clients.
|
|
207
|
+
|
|
208
|
+
**What happens to an unregistered custom class?** It travels as its closest known ancestor and keeps its name, so an unregistered `HttpError` comes back as an `Error` named `HttpError` with all its properties.
|
|
209
|
+
|
|
210
|
+
**Does it work with errors from `node:vm` or iframes?** Yes. Native classes from another realm are recognized by name, and `isError` checks the internal error slot instead of `instanceof`.
|
|
211
|
+
|
|
212
|
+
**Can I use it with `postMessage` without JSON?** Yes. The output of `serialize` is a plain value, so it can go through `postMessage` or `structuredClone` directly.
|
|
213
|
+
|
|
214
|
+
## Website
|
|
215
|
+
|
|
216
|
+
The website in `docs/` is built by `scripts/build-site.mjs` from `site/`. Built with [Monsoon](https://github.com/kwy404/monsoon), [Voodoo.js](https://github.com/kwy404/Voodoo.js) and [glyphfox](https://github.com/kwy404/glyphfox). Run `npm run site` and `npm run serve` to preview it.
|
|
217
|
+
|
|
218
|
+
## License
|
|
219
|
+
|
|
220
|
+
[MIT](LICENSE), Alexandre Kohler.
|
package/README.pt.md
ADDED
|
@@ -0,0 +1,220 @@
|
|
|
1
|
+
<picture>
|
|
2
|
+
<source media="(prefers-color-scheme: dark)" srcset="assets/banner-dark.svg">
|
|
3
|
+
<img alt="faultferry: envie erros entre processos e receba de volta inteiros" src="assets/banner-light.svg" width="100%">
|
|
4
|
+
</picture>
|
|
5
|
+
|
|
6
|
+
[English](README.md) | **Português (Brasil)** | [Español](README.es.md) | [日本語](README.ja.md)
|
|
7
|
+
|
|
8
|
+
[](https://github.com/kwy404/faultferry/actions/workflows/ci.yml)
|
|
9
|
+
[](https://www.npmjs.com/package/faultferry)
|
|
10
|
+
[](#tamanho)
|
|
11
|
+
[](package.json)
|
|
12
|
+
[](index.d.ts)
|
|
13
|
+
[](LICENSE)
|
|
14
|
+
|
|
15
|
+
**Serialize erros JavaScript para JSON puro e desserialize de volta, sem perder nada.** O faultferry mantém a classe, a mensagem, o stack, a cadeia de cause (com ciclos), AggregateError, SuppressedError, DOMException, classes de erro próprias e valores lançados que não são erros, para que você envie erros entre processos e receba de volta inteiros.
|
|
16
|
+
|
|
17
|
+
`JSON.stringify(new Error('boom'))` devolve `{}`. Workers, processos filhos, HTTP e filas de mensagens transportam dados, não erros, então a classe, a cadeia de cause e cada campo próprio se perdem no caminho. O faultferry transforma qualquer valor lançado em JSON puro e o reconstrói do outro lado: mesma classe, mensagem, stack, cadeia de cause (inclusive com ciclos), membros de AggregateError, campos de SuppressedError, name e code de DOMException e propriedades próprias. Ele nunca lança exceção com entradas maliciosas e não tem dependências.
|
|
18
|
+
|
|
19
|
+
Site e playground ao vivo: https://kwy404.github.io/faultferry/pt/
|
|
20
|
+
|
|
21
|
+
## Instalação
|
|
22
|
+
|
|
23
|
+
```sh
|
|
24
|
+
npm i faultferry
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
Builds ESM e CommonJS, tipos TypeScript escritos à mão, Node.js 18 ou mais recente, Bun, Deno e navegadores modernos.
|
|
28
|
+
|
|
29
|
+
## Começo rápido
|
|
30
|
+
|
|
31
|
+
```js
|
|
32
|
+
import { serialize, deserialize, register } from 'faultferry';
|
|
33
|
+
|
|
34
|
+
class HttpError extends Error {
|
|
35
|
+
constructor(message, status, options) {
|
|
36
|
+
super(message, options);
|
|
37
|
+
this.name = 'HttpError';
|
|
38
|
+
this.status = status;
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
register(HttpError); // nos dois lados
|
|
42
|
+
|
|
43
|
+
const error = new HttpError('checkout failed', 502, { cause: new TypeError('fetch failed') });
|
|
44
|
+
|
|
45
|
+
const wire = JSON.stringify(serialize(error));
|
|
46
|
+
const back = deserialize(JSON.parse(wire));
|
|
47
|
+
|
|
48
|
+
back instanceof HttpError; // true
|
|
49
|
+
back.status; // 502
|
|
50
|
+
back.cause instanceof TypeError; // true
|
|
51
|
+
back.stack === error.stack; // true
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
Através de um worker:
|
|
55
|
+
|
|
56
|
+
```js
|
|
57
|
+
// worker.js
|
|
58
|
+
self.onmessage = async ({ data }) => {
|
|
59
|
+
try {
|
|
60
|
+
postMessage({ ok: true, value: await run(data) });
|
|
61
|
+
} catch (error) {
|
|
62
|
+
postMessage({ ok: false, error: serialize(error) });
|
|
63
|
+
}
|
|
64
|
+
};
|
|
65
|
+
|
|
66
|
+
// main.js
|
|
67
|
+
worker.onmessage = ({ data }) => {
|
|
68
|
+
if (!data.ok) throw deserialize(data.error);
|
|
69
|
+
};
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
Do servidor para o navegador, sem vazar stack traces:
|
|
73
|
+
|
|
74
|
+
```js
|
|
75
|
+
app.use((error, req, res, next) => {
|
|
76
|
+
res.status(error.status ?? 500).json(serialize(error, { stack: false, maxDepth: 8 }));
|
|
77
|
+
});
|
|
78
|
+
```
|
|
79
|
+
|
|
80
|
+
## API
|
|
81
|
+
|
|
82
|
+
### `serialize(value, options?)`
|
|
83
|
+
|
|
84
|
+
Converte qualquer valor, normalmente algo que foi lançado, em um valor simples que `JSON.stringify`, `postMessage` e `structuredClone` aceitam. Nunca lança exceção com entradas maliciosas.
|
|
85
|
+
|
|
86
|
+
| opção | padrão | significado |
|
|
87
|
+
| --- | --- | --- |
|
|
88
|
+
| `maxDepth` | `32` | Limite de aninhamento. Contêineres mais fundos viram `"[Object]"`, `"[Array]"`, `"[Map]"` ou `"[Set]"`; erros mais fundos mantêm só classe, name e message. |
|
|
89
|
+
| `maxNodes` | `10000` | Total de contêineres e erros copiados antes que o mesmo corte seja aplicado. |
|
|
90
|
+
| `maxLength` | `Infinity` | Maior string mantida. Strings maiores são cortadas e terminam com `...`. |
|
|
91
|
+
| `maxItems` | `Infinity` | Máximo de itens de array, chaves de objeto e entradas de Map ou Set copiados por contêiner. |
|
|
92
|
+
| `stack` | `true` | Incluir stack traces. Passe `false` antes de enviar erros para clientes não confiáveis. |
|
|
93
|
+
| `toJSON` | `true` | Respeitar métodos `toJSON()`. Em um erro, o objeto devolvido substitui as propriedades próprias enumeráveis. |
|
|
94
|
+
| `classes` | `[]` | Classes de erro extras reconhecidas só nesta chamada. |
|
|
95
|
+
|
|
96
|
+
Um limite negativo ou não numérico lança `RangeError`; qualquer coisa em `classes` que não seja uma classe com nome lança `TypeError`. Esses são erros de programação, não problemas da entrada.
|
|
97
|
+
|
|
98
|
+
### `deserialize(data, options?)`
|
|
99
|
+
|
|
100
|
+
Reconstrói um valor produzido por `serialize()`. Erros voltam como objetos de erro de verdade, com o protótipo certo. Os construtores nunca são chamados, então argumentos obrigatórios do construtor não importam. Classes desconhecidas voltam como a classe conhecida mais próxima (normalmente `Error`) com o `name` original. Nunca lança exceção com entradas maliciosas.
|
|
101
|
+
|
|
102
|
+
| opção | padrão | significado |
|
|
103
|
+
| --- | --- | --- |
|
|
104
|
+
| `maxDepth` | `256` | Limite de aninhamento. Valores mais fundos viram `undefined`. Mantenha pelo menos tão alto quanto o `maxDepth` do serializador. |
|
|
105
|
+
| `classes` | `[]` | Classes de erro extras reconhecidas só nesta chamada. |
|
|
106
|
+
|
|
107
|
+
### `register(ErrorClass, name?)`
|
|
108
|
+
|
|
109
|
+
Registra uma classe de erro própria com o nome `name` (por padrão, o nome da classe) para que `deserialize()` consiga reconstruir suas instâncias. Devolve a classe. Registre as mesmas classes nos dois lados. Os erros nativos são sempre conhecidos: `Error`, `TypeError`, `RangeError`, `ReferenceError`, `SyntaxError`, `EvalError`, `URIError`, `AggregateError`, `SuppressedError` (onde existir) e `DOMException`.
|
|
110
|
+
|
|
111
|
+
### `unregister(classOrName)`
|
|
112
|
+
|
|
113
|
+
Remove uma classe registrada, pela classe ou pelo nome. Devolve `true` quando algo foi removido.
|
|
114
|
+
|
|
115
|
+
### `isError(value)`
|
|
116
|
+
|
|
117
|
+
`true` para objetos de erro de verdade, os que têm o slot interno `[[ErrorData]]`, inclusive erros de outros realms, como contextos `node:vm` e iframes. Usa o [`Error.isError`](https://tc39.es/proposal-is-error/) nativo quando o runtime tem. O fallback verifica `Object.prototype.toString` quando o valor não tem um `Symbol.toStringTag` próprio do tipo string e, caso contrário, consulta o `structuredClone`, que só clona como erro o que é erro de verdade. Objetos que apenas herdam de `Error.prototype` não são erros.
|
|
118
|
+
|
|
119
|
+
## O formato na rede
|
|
120
|
+
|
|
121
|
+
Um erro vira um objeto com `$error` (a chave no registro), `name`, `message`, `stack` e apenas os campos que ele realmente tinha:
|
|
122
|
+
|
|
123
|
+
```json
|
|
124
|
+
{
|
|
125
|
+
"$error": "HttpError",
|
|
126
|
+
"name": "HttpError",
|
|
127
|
+
"message": "checkout failed",
|
|
128
|
+
"stack": "HttpError: checkout failed\n at ...",
|
|
129
|
+
"cause": { "$error": "TypeError", "name": "TypeError", "message": "fetch failed", "stack": "..." },
|
|
130
|
+
"props": { "name": "HttpError", "status": 502 }
|
|
131
|
+
}
|
|
132
|
+
```
|
|
133
|
+
|
|
134
|
+
- `cause`, `errors` (AggregateError), `error` e `suppressed` (SuppressedError) só são escritos quando são propriedades próprias do erro.
|
|
135
|
+
- `props` guarda as propriedades próprias enumeráveis, ou o resultado de `toJSON()`.
|
|
136
|
+
- `code` é escrito para DOMException por legibilidade; na volta, quem decide o code é o name.
|
|
137
|
+
- Valores que o JSON não representa viram pequenos registros: `{ "$value": "undefined" }`, `NaN`, `Infinity`, `-Infinity`, `-0`, `bigint`, `Date`, `RegExp`, `Map` e `Set`.
|
|
138
|
+
- Ciclos e referências compartilhadas viram `{ "$ref": n }`, em que `n` é a posição do contêiner de destino em um percurso em profundidade. Eles voltam com a mesma identidade.
|
|
139
|
+
- Um objeto simples cujas chaves coincidem com essas marcas é embrulhado em `{ "$escape": ... }`, então dados nunca viram erro por acidente.
|
|
140
|
+
- Funções viram `"[Function: name]"` e símbolos viram `"Symbol(description)"`.
|
|
141
|
+
|
|
142
|
+
## Notas de comportamento
|
|
143
|
+
|
|
144
|
+
- Propriedades próprias enumeráveis voltam enumeráveis; `message`, `stack`, `cause`, `errors`, `error` e `suppressed` voltam não enumeráveis, como a linguagem as cria ([ECMA-262 InstallErrorCause](https://tc39.es/ecma262/#sec-installerrorcause), [AggregateError](https://tc39.es/ecma262/#sec-aggregate-error-objects)).
|
|
145
|
+
- Um erro que nunca teve stack volta sem stack; o erro reconstruído nunca ganha um stack novo do lugar onde o `deserialize` rodou.
|
|
146
|
+
- Getters que lançam exceção, proxies revogados e armadilhas de protótipo são ignorados, nunca seguidos de uma exceção. Um getter de `message` que lança exceção vira uma mensagem ausente.
|
|
147
|
+
- Chaves `__proto__` são guardadas e restauradas como dados comuns com `Object.defineProperty`, então não conseguem trocar um protótipo.
|
|
148
|
+
- Uma string lançada volta como a mesma string. Nada é embrulhado em um erro falso.
|
|
149
|
+
|
|
150
|
+
## Comparado com structuredClone
|
|
151
|
+
|
|
152
|
+
Verificado no Node 24 por `test/structured-clone.test.js`.
|
|
153
|
+
|
|
154
|
+
| Depois da ida e volta | faultferry | structuredClone |
|
|
155
|
+
| --- | --- | --- |
|
|
156
|
+
| Saída | Valor seguro para JSON, qualquer transporte | Só canais de clonagem estruturada, sem texto |
|
|
157
|
+
| Instância de classe própria | Mesma classe (registrada) | `Error` comum |
|
|
158
|
+
| `errors` do AggregateError | Mantém | Perde, volta como `Error` |
|
|
159
|
+
| SuppressedError | Mantém | Perde |
|
|
160
|
+
| Propriedades próprias (`status`, `code`) | Mantém | Descarta |
|
|
161
|
+
| cause circular | Mantém | Mantém |
|
|
162
|
+
| name e code de DOMException | Mantém | Mantém |
|
|
163
|
+
| Função em uma cause ou prop | Vira `"[Function: name]"` | Lança `DataCloneError` |
|
|
164
|
+
| Proxy em qualquer lugar do grafo | Lido com segurança ou ignorado | Lança `DataCloneError` |
|
|
165
|
+
| Getter de `message` que lança exceção | Ignorado | Lança exceção |
|
|
166
|
+
|
|
167
|
+
## Por que não o serialize-error?
|
|
168
|
+
|
|
169
|
+
O serialize-error é o pacote tradicional para essa tarefa. O faultferry faz escolhas diferentes, todas verificadas com o serialize-error 13.1.0 no Node 24 em uma pasta de rascunho:
|
|
170
|
+
|
|
171
|
+
- Lá, uma cause circular vira a string `"[Circular]"`; aqui ela é restaurada como o mesmo objeto.
|
|
172
|
+
- Lá, referências compartilhadas são duplicadas; aqui elas mantêm a identidade.
|
|
173
|
+
- Lá, um DOMException volta como Error comum com `name` e `code`; aqui ele é um DOMException.
|
|
174
|
+
- Lá, `error` e `suppressed` do SuppressedError se perdem; aqui eles são mantidos.
|
|
175
|
+
- Lá, strings lançadas são embrulhadas em `NonError`; aqui continuam strings. Lá, `undefined` é descartado, `NaN` vira `null`, BigInt vira `"10n"` e Date vira string; aqui eles voltam como os mesmos valores.
|
|
176
|
+
- Um getter de propriedade própria que lança exceção, ou um proxy revogado, faz o serialize-error lançar exceção; o faultferry nunca lança exceção por causa da entrada.
|
|
177
|
+
- Classes próprias precisam de `addKnownErrorConstructor` lá e de `register` aqui; os dois funcionam.
|
|
178
|
+
|
|
179
|
+
O serialize-error tem uma base de usuários muito maior e um histórico mais longo. Se o formato de saída dele já serve para o seu sistema, ele é uma ótima escolha.
|
|
180
|
+
|
|
181
|
+
## Benchmarks
|
|
182
|
+
|
|
183
|
+
`npm run bench`, operações por segundo, mediana de cinco execuções, maior é melhor. Node 24.16.0, AMD Ryzen 7 7800X3D, Windows x64, 2026-12-04.
|
|
184
|
+
|
|
185
|
+
| caso | faultferry serialize | serialize-error serialize | faultferry deserialize | serialize-error deserialize | structuredClone (sem JSON) |
|
|
186
|
+
| --- | ---: | ---: | ---: | ---: | ---: |
|
|
187
|
+
| simple TypeError | 1.65M | 893k | 548k | 143k | 697k |
|
|
188
|
+
| cause chain x6 | 319k | 160k | 98k | 10k | 193k |
|
|
189
|
+
| error with props | 821k | 426k | 313k | 121k | 757k |
|
|
190
|
+
| AggregateError x20 | 68k | 40k | 22k | 3k | 638k |
|
|
191
|
+
|
|
192
|
+
Serialize inclui `JSON.stringify`; deserialize inclui `JSON.parse`. O structuredClone não gera JSON e descarta os membros do AggregateError, por isso é tão rápido nesse caso. O serialize-error é instalado só para o benchmark e não é uma dependência.
|
|
193
|
+
|
|
194
|
+
## Tamanho
|
|
195
|
+
|
|
196
|
+
4.7 kB com gzip, sem comentários nem espaços (7.0 kB com gzip como publicado, com JSDoc). `npm run size` mostra os números. Zero dependências em runtime, `sideEffects: false`.
|
|
197
|
+
|
|
198
|
+
## Compatibilidade
|
|
199
|
+
|
|
200
|
+
Node.js 18 ou mais recente (testado nas versões 18, 20, 22 e 24 no CI, em Linux, Windows e macOS), Bun e Deno (smoke tests no CI), navegadores modernos, Web Workers e Service Workers. O suporte a `SuppressedError` é ativado onde o runtime o tiver.
|
|
201
|
+
|
|
202
|
+
## Perguntas frequentes
|
|
203
|
+
|
|
204
|
+
**Por que `JSON.stringify(error)` devolve `{}`?** `message`, `stack` e `cause` são propriedades próprias não enumeráveis, e o `JSON.stringify` só escreve as enumeráveis. O `serialize(error)` copia esses campos para um objeto simples antes, e o `deserialize` transforma esse objeto de volta em um erro de verdade.
|
|
205
|
+
|
|
206
|
+
**É seguro desserializar dados vindos da rede?** O `deserialize` nunca chama construtores nem getters dos dados, nunca altera protótipos e trata chaves `__proto__` como dados comuns. Ele só constrói as classes que você registrou. Passe `stack: false` ao serializar para clientes não confiáveis.
|
|
207
|
+
|
|
208
|
+
**O que acontece com uma classe própria não registrada?** Ela viaja como o ancestral conhecido mais próximo e mantém o nome, então um `HttpError` não registrado volta como um `Error` chamado `HttpError`, com todas as suas propriedades.
|
|
209
|
+
|
|
210
|
+
**Funciona com erros de `node:vm` ou de iframes?** Sim. Classes nativas de outro realm são reconhecidas pelo nome, e o `isError` verifica o slot interno de erro em vez de `instanceof`.
|
|
211
|
+
|
|
212
|
+
**Posso usar com `postMessage` sem JSON?** Sim. A saída do `serialize` é um valor simples, então ela pode passar direto por `postMessage` ou `structuredClone`.
|
|
213
|
+
|
|
214
|
+
## Site
|
|
215
|
+
|
|
216
|
+
O site em `docs/` é gerado por `scripts/build-site.mjs` a partir de `site/`. Feito com [Monsoon](https://github.com/kwy404/monsoon), [Voodoo.js](https://github.com/kwy404/Voodoo.js) e [glyphfox](https://github.com/kwy404/glyphfox). Rode `npm run site` e `npm run serve` para ver uma prévia.
|
|
217
|
+
|
|
218
|
+
## Licença
|
|
219
|
+
|
|
220
|
+
[MIT](LICENSE), Alexandre Kohler.
|