Skip to content

Commit

Permalink
doc: improve example for Error.captureStackTrace()
Browse files Browse the repository at this point in the history
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 <ruben@bridgewater.de>
PR-URL: #46886
Reviewed-By: James M Snell <jasnell@gmail.com>
Reviewed-By: Debadree Chatterjee <debadree333@gmail.com>
Reviewed-By: Luigi Pinca <luigipinca@gmail.com>
  • Loading branch information
2 people authored and RafaelGSS committed Apr 6, 2023
1 parent 950883e commit ab2f699
Showing 1 changed file with 19 additions and 6 deletions.
25 changes: 19 additions & 6 deletions doc/api/errors.md
Original file line number Diff line number Diff line change
Expand Up @@ -232,14 +232,27 @@ The `constructorOpt` argument is useful for hiding implementation
details of error generation from the user. For instance:

```js
function MyError() {
Error.captureStackTrace(this, MyError);
function a() {
b();
}

// Without passing MyError to captureStackTrace, the MyError
// frame would show up in the .stack property. By passing
// the constructor, we omit that frame, and retain all frames below it.
new MyError().stack;
function b() {
c();
}

function c() {
// Create an error without stack trace to avoid calculating the stack trace twice.
const { stackTraceLimit } = Error;
Error.stackTraceLimit = 0;
const error = new Error();
Error.stackTraceLimit = stackTraceLimit;

// Capture the stack trace above function b
Error.captureStackTrace(error, b); // Neither function c, nor b is included in the stack trace
throw error;
}

a();
```

### `Error.stackTraceLimit`
Expand Down

0 comments on commit ab2f699

Please sign in to comment.