Open In App

Node.js util.getSystemErrorName() Method

The util.getSystemErrorName() method is defined in utilities module of Node.js standard library. It is used to know the type of error that occurs in the program. Generally, this method is used within some other method to know if that method does not give response as expected because some error occurs then what type of error that was to ensure that our program does break.

Syntax



util.getSystemErrorName( err )

Parameters: This method accepts a single parameter ‘err’ that holds a numerical value that specifies the error number or error code. This error code comes from Node.js API itself.

Return Value: Returns a string name i.e. error name for a numeric error code.



Note: There are some common system error that are mapped to specific error code. The mapping between system error and error code is platform dependent. Some common system errors are shown below.

Example 1:




// Importing File System module
const fs = require('fs')
  
// Importing utilities module
const util = require('util')
  
fs.readdir('file/not/exist', (err, files) => {
  if(err){
    const errName = util.getSystemErrorName(err.errno)
    console.log(`Error Name --> ${errName}`)
    console.log(`Error Code --> ${err.errno}`)
  }else{
    for(let file in files){
      console.log(file)
    }
  
}) 

Output:

Error Name --> ENOENT
Error Code --> 4058

Explanation: Program is basically to fetch all the files and folders in a given directory. The fs.readdir() method takes path to the target directory. In case, if the given path is not valid then an error occurs which may break our program and so have to handle the error and provide the user some valid output so that the user aware of why an error occurs. Here to handle the error getSystemErrorName() method is used which returns the name of the error that occurs.

Example 2:




// Importing File System module
const fs = require('fs')
  
// Importing utilities module
const util = require('util')
  
fs.readdir('./index.js', (err, files) => {
  if(err){
    const errName = util.getSystemErrorName(err.errno)
    console.log(`Error Name --> ${errName}`)
    console.log(`Error Code --> ${err.errno}`)
  }else{
    for(let file in files){
      console.log(file)
    }
  
}) 

Output:

Error Name --> ENOTDIR
Error Code --> 4052

Explanation: Program is basically to fetch all the files and folders in a given directory. The fs.readdir() method takes the path to the target directory. Since the given path is not a directory but a file, an error named ENOTDIR occurs.


Article Tags :