Dimitrios Desyllas
Dimitrios Desyllas

Reputation: 10124

Nodejs fs file handling: Getting error type in order to handle it more efficient

I have the very simple function reading a json file:

const loadJsonContentFromFile=function(path,callback){
    fs.readFile(path, 'utf8', function (err, data) {
      if (err){
        return callback(err)
      }
      try {
        const obj = JSON.parse(data);
        return callback(null,obj);
      } catch(error){
        return callback(error);
      }
    });
}

But I want further indications on the err object regarding the file reading. In other words I want to know why the fs.readFile failed to read the file in order to provide into the callback a tailor made response message instead of the ones that nodejs by default provides, for example if sustem user does not have the permissions to read the file I want to provide a message like:

Your user has not the correct wrights to read the file ./somefile.txt please run sudo chmod +r ./somefile.txt in order to give the right permissions.

Whilst if the file does not exists I want to provide an error message like:

The file ./somefile.txt does not exist

It sounds trivial but I think is a good example to fine-handle an error that has been returned. In order to achieve that I want to be able to identify the error that readFile callback accepts as an argument.

In php I would use the Error object's class name in order to figure out what type of error is. But in Node.js how I can do that?

NOTE:

I know that an approach to the problem's solution is to check before reading the file if the file exists and has the correct permissions. But I believe that is not the only one solution so I am looking for an alternate one on the existing problem.

Upvotes: 1

Views: 573

Answers (1)

Marcos Casagrande
Marcos Casagrande

Reputation: 40444

You can check against err.code and return a custom error that suits your needs.

const loadJsonContentFromFile = function(path,callback) {

    fs.readFile(path, 'utf8', function(err, data) {
        if(err) {

            if(err.code === 'EACCESS') {
                return callback(
                    // Or create your custom error: ForbiddenError...
                    new Error('Your user has not the correct permissions to read the file...')
                );
            }

            if(err.code === 'ENOENT') {

                return callback(
                    new Error(`The file ${path} does not exist`)
                );
            }

        }

        /** ... **/ 
    });
}

You can check the docs for more error codes.

Upvotes: 1

Related Questions