GeezerVison is showing github.com — doc: improve example for Error.captureStackTrace() · nodejs/node@7124624
File tree
Expand file treeCollapse file tree
Open diff view settings
Expand file treeCollapse file tree
Open diff view settings
Collapse file
Copy file name to clipboardExpand all lines: doc/api/errors.md +19-6Lines changed: 19 additions & 6 deletions - Display the source diff
- Display the rich diff
| Original file line number | Diff line number | Diff line change |
|---|
@@ -232,14 +232,27 @@ The `constructorOpt` argument is useful for hiding implementation |
232 | 232 | details of error generation from the user. For instance: |
233 | 233 |
|
234 | 234 | ```js |
235 | | -function MyError() { |
236 | | - Error.captureStackTrace(this, MyError); |
| 235 | +function a() { |
| 236 | + b(); |
237 | 237 | } |
238 | 238 |
|
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(); |
243 | 256 | ``` |
244 | 257 |
|
245 | 258 | ### `Error.stackTraceLimit` |
|