What is the Node function Util.isError(object)?
In this shot, we will learn about the function util.isError(), which is provided by the in-built Util module in Node.
The util.isError() method is used to check whether the object passed as a parameter is an error object or not.
Syntax
var isError = util.isError(object);
Parameter
This function takes only one argument of type object. You can pass any object type.
Return type
The util.isError(object) returns a boolean value.
-
true: If the object is anErrorobject. -
false: If the object is not anErrorobject.
var util = require('util');var error = new Error();var typeError = new TypeError();var isErr = util.isError(error);console.log(isErr);isErr = util.isError(typeError)console.log(isErr);isErr = util.isError({name: 'Ayush',message: 'No error'});console.log(isErr);
Let’s break down the code. The above is a example of the util.isError() method.
-
In line 1, we import the
utilmodule. -
In line 3, we create a object of
error. -
In line 4, we create a new object of
errorof typeTypeError. -
In lines 6, 9, and 12, we store the boolean value returned by
util.isError()in the variable nameisErr. -
In lines 7, 10, and 16, we log the boolean value returned by the function
util.isError().
Output
The above code gives an output true, true, and false, as expected. The first two lines of output are true because we have passed Object of Error in the util.isError() method. As both the objects are error, it returns a true boolean value. The last line of output is false because the object passed is not an error object and hence util.isError() returns false.