@@ -2515,14 +2515,46 @@ added: v10.0.0
2515
2515
* ` value` {any}
2516
2516
* Returns: {boolean}
2517
2517
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][].
2519
2520
2520
2521
` ` ` js
2521
2522
util .types .isNativeError (new Error ()); // Returns true
2522
2523
util .types .isNativeError (new TypeError ()); // Returns true
2523
2524
util .types .isNativeError (new RangeError ()); // Returns true
2524
2525
` ` `
2525
2526
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
+
2526
2558
### ` util .types .isNumberObject (value)`
2527
2559
2528
2560
<!-- YAML
@@ -3287,6 +3319,8 @@ util.log('Timestamped message.');
3287
3319
[Customizing ` util .inspect ` colors]: #customizing-utilinspect-colors
3288
3320
[Internationalization]: intl.md
3289
3321
[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
3290
3324
[WHATWG Encoding Standard]: https://encoding.spec.whatwg.org/
3291
3325
[` ' uncaughtException' ` ]: process.md#event-uncaughtexception
3292
3326
[` ' warning' ` ]: process.md#event-warning
0 commit comments