Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/35.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Node.js Nodejs fs文件处理:获取错误类型以便更有效地处理它_Node.js_Error Handling - Fatal编程技术网

Node.js Nodejs fs文件处理:获取错误类型以便更有效地处理它

Node.js Nodejs fs文件处理:获取错误类型以便更有效地处理它,node.js,error-handling,Node.js,Error Handling,我有一个非常简单的函数来读取json文件: const loadJsonContentFromFile=function(path,callback){ fs.readFile(path, 'utf8', function (err, data) { if (err){ return callback(err) } try { const obj = JSON.parse(data); return ca

我有一个非常简单的函数来读取json文件:

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);
      }
    });
}
但是我想在
err
对象上进一步说明文件读取。换句话说,我想知道为什么
fs.readFile
无法读取文件,以便向
回调中提供定制的响应消息,而不是nodejs默认提供的响应消息,例如,如果sustem用户没有读取文件的权限,我想提供如下消息:

您的用户没有读取文件的正确权限。/somefile.txt请运行sudo chmod+r./somefile.txt以授予正确的权限

如果文件不存在,我想提供一条错误消息,如:

文件./somefile.txt不存在

这听起来很简单,但我认为这是一个很好的例子,可以很好地处理返回的错误。为了实现这一点,我希望能够识别
readFile
callback作为参数接受的错误

在php中,我会使用Error对象的类名来确定错误的类型。但在Node.js中,我如何做到这一点

注意:


我知道解决问题的一种方法是在读取文件之前检查该文件是否存在并且具有正确的权限。但我相信这不是唯一的解决方案,因此我正在寻找一个解决现有问题的替代方案。

您可以检查
err.code
并返回符合您需要的自定义错误

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`)
                );
            }

        }

        /** ... **/ 
    });
}
您可以检查更多错误代码