From 0286b652ae9738335b8ee5ac0bf504f32436ebc9 Mon Sep 17 00:00:00 2001 From: Julian Dax Date: Sun, 26 Feb 2023 00:38:59 +0100 Subject: [PATCH 01/12] doc: improve documentation for util.types.isNativeError() Makes clear what a native error is by linking the spec. Explains that `instanceof Error` and util.types.isNativeError() are not equivalent. Give examples for objects that are `instance of Error` but not native errors and vice versa. Recommends checking for both if one wants to find out if something is an error. --- doc/api/util.md | 36 +++++++++++++++++++++++++++++++++++- 1 file changed, 35 insertions(+), 1 deletion(-) diff --git a/doc/api/util.md b/doc/api/util.md index a0554a40b2ae8c..a447730591e557 100644 --- a/doc/api/util.md +++ b/doc/api/util.md @@ -2515,7 +2515,8 @@ added: v10.0.0 * `value` {any} * Returns: {boolean} -Returns `true` if the value is an instance of a built-in [`Error`][] type. +Returns `true` if the value was returned by the constructor of a +[built-in `Error` type][]. ```js util.types.isNativeError(new Error()); // Returns true @@ -2523,6 +2524,37 @@ util.types.isNativeError(new TypeError()); // Returns true util.types.isNativeError(new RangeError()); // Returns true ``` +Subclasses of the native error types will use the return value of the native +error constructor as the new `this` and are therefore also native errors: + +```js +class MyError extends Error {} +util.types.isNativeError(new MyError()); // Returns true +``` + +A value being `instanceof` a native error is not equivalent to `isNativeError()` +returning `true` for that value. Therefore, we recommend using +`isNativeError(e) || e instanceof Error` to check if `e` is an error. + +`isNativeError()` returns `true` for errors which come from a different +[realm][] while `instanceof Error` returns `false` for these errors: + +```js +const vm = require('vm'); +const context = vm.createContext({}); +util.types.isNativeError(vm.runInContext('new Error()', context)); // Returns true +vm.runInContext('new Error()', context) instanceof Error; // Returns false +``` + +Conversely, `isNativeError()` returns `false` for all objects which where not +returned by the constructor of a native error. That includes values +which are `instanceof` native errors: + +```js +util.types.isNativeError({__proto__: Error.prototype}); // Returns false +({__proto__: Error.prototype} instanceof Error); // Returns true +``` + ### `util.types.isNumberObject(value)`