@@ -2515,14 +2515,46 @@ added: v10.0.0
25152515* ` value` {any}
25162516* Returns: {boolean}
25172517
2518- Returns ` true ` if the value is an instance of a built-in [` Error ` ][] type.
2518+ Returns ` true ` if the value was returned by the constructor of a
2519+ [built-in ` Error ` type][].
25192520
25202521` ` ` js
25212522util .types .isNativeError (new Error ()); // Returns true
25222523util .types .isNativeError (new TypeError ()); // Returns true
25232524util .types .isNativeError (new RangeError ()); // Returns true
25242525` ` `
25252526
2527+ Subclasses of the native error types will use the return value of the native
2528+ error constructor as the new ` this ` and are therefore also native errors:
2529+
2530+ ` ` ` js
2531+ class MyError extends Error {}
2532+ util .types .isNativeError (new MyError ()); // Returns true
2533+ ` ` `
2534+
2535+ A value being ` instanceof ` a native error is not equivalent to ` isNativeError ()`
2536+ returning ` true ` for that value. Therefore, we recommend using
2537+ ` isNativeError (e) || e instanceof Error ` to check if ` e` is an error.
2538+
2539+ ` isNativeError ()` returns ` true ` for errors which come from a different
2540+ [realm][] while ` instanceof Error ` returns ` false ` for these errors:
2541+
2542+ ` ` ` js
2543+ const vm = require (' vm' );
2544+ const context = vm .createContext ({});
2545+ util .types .isNativeError (vm .runInContext (' new Error()' , context)); // Returns true
2546+ vm .runInContext (' new Error()' , context) instanceof Error ; // Returns false
2547+ ` ` `
2548+
2549+ Conversely, ` isNativeError ()` returns ` false ` for all objects which where not
2550+ returned by the constructor of a native error. That includes values
2551+ which are ` instanceof ` native errors.
2552+
2553+ ` ` ` js
2554+ util .types .isNativeError ({__proto__: Error .prototype }); // Returns false
2555+ ({__proto__: Error .prototype } instanceof Error ); // Returns true
2556+ ` ` `
2557+
25262558### ` util .types .isNumberObject (value)`
25272559
25282560<!-- YAML
@@ -3287,6 +3319,8 @@ util.log('Timestamped message.');
32873319[Customizing ` util .inspect ` colors]: #customizing-utilinspect-colors
32883320[Internationalization]: intl.md
32893321[Module Namespace Object]: https://tc39.github.io/ecma262/#sec-module-namespace-exotic-objects
3322+ [realm]: https://tc39.es/ecma262/#realm
3323+ [built-in ` Error ` type]: https://tc39.es/ecma262/#sec-error-objects
32903324[WHATWG Encoding Standard]: https://encoding.spec.whatwg.org/
32913325[` ' uncaughtException' ` ]: process.md#event-uncaughtexception
32923326[` ' warning' ` ]: process.md#event-warning
0 commit comments