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.
var isError = util.isError(object);
This function takes only one argument of type object
. You can pass any object type.
The util.isError(object)
returns a boolean value.
true
: If the object is an Error
object.
false
: If the object is not an Error
object.
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 util
module.
In line 3, we create a object of error
.
In line 4, we create a new object of error
of type TypeError
.
In lines 6, 9, and 12, we store the boolean value returned by util.isError()
in the variable name isErr
.
In lines 7, 10, and 16, we log the boolean value returned by the function util.isError()
.
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
.