Node.js – util.types.isNativeError() Method


The util.types.isNativeError() method checks whether the passed value is a built-in error type or not. If the above condition is satisfied, it returns True, else False. The error can be of any type.

Syntax

util.types.isNativeError(value)

Parameters

It takes a single parameter −

  • value − This input value takes input for the required parameter and checks if it's an error type or not.

It returns True or False based upon the input value passed.

Example 1

Create a file with the name "isNativeError.js" and copy the following code snippet. After creating the file, use the command "node isNativeError.js" to run this code.

// util.types.isNativeError() Demo Example

// Importing the util module
const util = require('util');

// Passing a new error instance to the input param
console.log("1." + util.types.isNativeError(new Error()));

// Passing a TypeError to the input param
console.log("2." + util.types.isNativeError(new TypeError()));

// Passing a RangeError to the input param
console.log("3." + util.types.isNativeError(new RangeError()));

Output

C:\home
ode>> node isNativeError.js 1.true 2.true 3.true

Example 2

Let’s have a look at one more example

// Importing the util & assert module
const util = require('util');
const assert = require('assert');

function fun() {
   return new Error('Some Unknown Error occured')
}

function fun1() {
   return (5/0); // Will return infinity
}

// Passing a new error returned from function
console.log("1." + util.types.isNativeError(fun()));

// Passing a mathmeatical error
console.log("2." + util.types.isNativeError(fun1()));

// Passing an AssertionError to the input param
console.log("3." + util.types.isNativeError(assert.AssertionError));

Output

C:\home
ode>> node isNativeError.js 1.true 2.false 3.false

Updated on: 18-Aug-2021

71 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements