Skip to content

Commit

Permalink
doc: improve documentation for Error.captureStackTrace()
Browse files Browse the repository at this point in the history
add improvements by @BridgeAR
  • Loading branch information
brodo committed Mar 1, 2023
1 parent d6b4d43 commit c4b05b3
Showing 1 changed file with 16 additions and 18 deletions.
34 changes: 16 additions & 18 deletions doc/api/errors.md
Expand Up @@ -232,31 +232,29 @@ The `constructorOpt` argument is useful for hiding implementation
details of error generation from the user. For instance:

```js
function MyError() {
// Set the stack trace limit to zero to avoid calculating the stack trace twice.
function a() {
b();
}

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 instance = new Error();
const error = new Error();
Error.stackTraceLimit = stackTraceLimit;
Error.captureStackTrace(instance, MyError);
return instance;
}

// 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;
```

We recommend using classes that extend `Error` for custom errors:
// Capture the stack trace above function b
Error.captureStackTrace(error, b); // Neither function c, nor b is included in the stack trace
throw error;
}

```js
class MyError extends Error {}
a();
```

Instances of this class are native errors with are instances of `Error` and have
a correct stack trace.

### `Error.stackTraceLimit`

* {number}
Expand Down

0 comments on commit c4b05b3

Please sign in to comment.