Node.js assert.fail() Function
Last Updated :
07 Aug, 2020
Improve
The assert module provides a set of assertion functions for verifying invariants. The assert.fail() function throws an AssertionError with the provided the error message or with a default error message.
Syntax:
javascript
Steps to run the program:
javascript
Steps to run the program:
assert.fail([message])Parameters: This function accepts following parameters as mentioned above and described below:
- message This parameter holds the error message of string or error type. It is an optional parameter.
- You can visit the link to Install assert module. You can install this package by using this command.
npm install assert
Note: Installation is an optional step as it is inbuilt Node.js module. - After installing the assert module, you can check your assert version in command prompt using the command.
npm version assert
- After that, you can just create a folder and add a file for example, index.js as shown below.
// Requiring the module
const assert = require('assert').strict;
// Function call
try {
assert.fail();
} catch(error) {
console.log("Error:", error)
}
- The project structure will look like this:
- Run index.js file using below command:
node index.js
Output:Error: AssertionError [ERR_ASSERTION]: Failed at Object. (C:\Users\Lenovo\Downloads\index.js:6:12) at Module._compile (internal/modules/cjs/loader.js:1138:30) at Object.Module._extensions..js (internal/modules/cjs/loader.js:1158:10) at Module.load (internal/modules/cjs/loader.js:986:32) at Function.Module._load (internal/modules/cjs/loader.js:879:14) at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:71:12) at internal/main/run_main_module.js:17:47 { generatedMessage: true, code: 'ERR_ASSERTION', actual: undefined, expected: undefined, operator: 'fail' }
// Requiring the module
const assert = require('assert').strict;
// Function call
try {
assert.fail(new TypeError('My custom defined error'));
} catch(error) {
console.log("Error:", error)
}
- The project structure will look like this:
- Run index.js file using below command:
node index.js
Output:Error: TypeError: My custom defined error at Object. (C:\Users\Lenovo\Downloads\index.js:6:17) at Module._compile (internal/modules/cjs/loader.js:1138:30) at Object.Module._extensions..js (internal/modules/cjs/loader.js:1158:10) at Module.load (internal/modules/cjs/loader.js:986:32) at Function.Module._load (internal/modules/cjs/loader.js:879:14) at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:71:12) at internal/main/run_main_module.js:17:47