From 71246247a9ca39f4171d48fd62a964d98d71d069 Mon Sep 17 00:00:00 2001 From: Julian Dax Date: Sun, 26 Mar 2023 22:38:27 +0200 Subject: [PATCH] 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 PR-URL: https://github.com/nodejs/node/pull/46886 Reviewed-By: James M Snell Reviewed-By: Debadree Chatterjee Reviewed-By: Luigi Pinca --- doc/api/errors.md | 25 +++++++++++++++++++------ 1 file changed, 19 insertions(+), 6 deletions(-) diff --git a/doc/api/errors.md b/doc/api/errors.md index a895dd5a5af904..396a5c594fbf12 100644 --- a/doc/api/errors.md +++ b/doc/api/errors.md @@ -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`