What is the fail method of the assert module in Node.js?

The fail method of the assert module in Node.js throws an AssertionError with an error message.

The process is illustrated below:

To use the fail method, you will need to install the assert module using the command prompt, as shown below:

npm install assert

After the installation is complete, you will need to import the assert module into the program, as shown below:

const assert = require('assert');

The prototype of the fail method is shown below:

fail([message])

Parameters

The fail method takes a single optional parameter that may either be an error message or an instance of an Error object.

Return value

The fail method throws an AssertionError with the provided message parameter. If the message parameter is not provided, a default error message is assigned.

Similarly, if the message parameter is an instance of an Error object, then the Error instance is thrown instead of the AssertionError.

Example

The code below shows how the fail method works in Node.js:

const assert = require('assert');
// default error message
try{
assert.fail()
}
catch(error){
console.log(error.message)
}
// provided error message
try{
assert.fail('This error message should be displayed')
}
catch(error){
console.log(error.message)
}
// provided Error object
try{
assert.fail(new TypeError('My custom error object'))
}
catch(error){
console.log(error.message)
}

Explanation

The code above uses three different expressions to show the behavior of the fail method.

In the first call to the fail method in line 55, no message parameter is provided. The fail method proceeds to throw an error, which triggers the catch branch of the try-catch block. The code outputs the message associated with the error, i.e., the default message associated with the fail method.

In the call to the fail method in line 1313, the message parameter is provided. The fail method proceeds to throw an error, which triggers the catch branch of the try-catch block. The code outputs the message associated with the error, i.e., the provided message parameter.

In the call to the fail method in line 1919, the message parameter is an instance of an Error object. The fail method proceeds to throw an error, which triggers the catch branch of the try-catch block. The code outputs the message associated with the Error instance, i.e., the initialized string.

Copyright ©2024 Educative, Inc. All rights reserved