Skip to content

Commit 7124624

Browse files
brodoBridgeAR
authored andcommitted
doc: improve example for Error.captureStackTrace()
Change the `MyError` example so that instances of `MyError`are `instanceof Error` and also native errors when checked with `util.types.isNativeError()`. Co-authored-by: Ruben Bridgewater <[email protected]> PR-URL: #46886 Reviewed-By: James M Snell <[email protected]> Reviewed-By: Debadree Chatterjee <[email protected]> Reviewed-By: Luigi Pinca <[email protected]>
1 parent 0b2ba44 commit 7124624

File tree

1 file changed

+19
-6
lines changed

1 file changed

+19
-6
lines changed

doc/api/errors.md

+19-6
Original file line numberDiff line numberDiff line change
@@ -232,14 +232,27 @@ The `constructorOpt` argument is useful for hiding implementation
232232
details of error generation from the user. For instance:
233233

234234
```js
235-
function MyError() {
236-
Error.captureStackTrace(this, MyError);
235+
function a() {
236+
b();
237237
}
238238

239-
// Without passing MyError to captureStackTrace, the MyError
240-
// frame would show up in the .stack property. By passing
241-
// the constructor, we omit that frame, and retain all frames below it.
242-
new MyError().stack;
239+
function b() {
240+
c();
241+
}
242+
243+
function c() {
244+
// Create an error without stack trace to avoid calculating the stack trace twice.
245+
const { stackTraceLimit } = Error;
246+
Error.stackTraceLimit = 0;
247+
const error = new Error();
248+
Error.stackTraceLimit = stackTraceLimit;
249+
250+
// Capture the stack trace above function b
251+
Error.captureStackTrace(error, b); // Neither function c, nor b is included in the stack trace
252+
throw error;
253+
}
254+
255+
a();
243256
```
244257

245258
### `Error.stackTraceLimit`

0 commit comments

Comments
 (0)