assert.ifError() function in Node.js

Node.jsJavascriptWeb DevelopmentFront End Technology

The assert module provides a bunch of different functionalities that are used for function assertion. Assert.ifError() function provides a functionality to throw an error if the value is not null or undefined. An error will be thrown if the value is not two of them.

Syntax

assert.ifError(value)

Parameters

The above parameters are described as below −

  • value – This paramter will hold the value to be checked for error. It will throw error in all cases except when the value is 'null' or 'undefined'.

Installing the Assert Module

npm install assert

The assert module is an inbuilt Node.js module, so you can skip this step as well. You can check the assert version using the following command to get the latest assert module.

npm version assert

Importing the module in your function

const assert = require("assert").strict;

Example

Create a file with the name – assertIfError.js and copy the below code snippet. After creating the file use the below command to run this code.

node assertIfError.js

assertIfError.js

 Live Demo

// Importing the module
const assert = require('assert').strict;

try {
   assert.ifError('6');
// Will throw an error: value: 6
} catch(error) {
   console.log("Error:", error)
}

Output

C:\home\node>> node assertIfError.js
Error: { AssertionError [ERR_ASSERTION]: ifError got unwanted exception: '6'
      at Object. (/home/node/mysql-test/assert.js:5:9)
      at Module._compile (internal/modules/cjs/loader.js:778:30)
      at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)
      at Module.load (internal/modules/cjs/loader.js:653:32)
      at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
      at Function.Module._load (internal/modules/cjs/loader.js:585:3)
      at Function.Module.runMain (internal/modules/cjs/loader.js:831:12)
      at startup (internal/bootstrap/node.js:283:19)
      at bootstrapNodeJSCore (internal/bootstrap/node.js:623:3)
   generatedMessage: false,
   name: 'AssertionError [ERR_ASSERTION]',
   code: 'ERR_ASSERTION',
   actual: '6',
   expected: null,
   operator: 'ifError' }

We can see in the above example that that the value is not null or undefined.

Example

Let's take a look at one more example.

// Importing the module
const assert = require('assert').strict;

try {
   assert.ifError(null);
   console.log("No Error occured")
   assert.ifError(undefined);
   console.log("OK")
   // Value: undefined & null is valid
} catch(error) {
   console.log("Error:", error)
}

Output

C:\home\node>> node assertIfError.js
No Error occured
OK

We can see in the above example that the values are null and undefined which are valid values for ifError in assert.

raja
Published on 20-May-2021 11:32:51
Advertisements