Skip to content

Commit

Permalink
fix: handle errors properly (#8)
Browse files Browse the repository at this point in the history
  • Loading branch information
thecodrr committed Mar 21, 2020
1 parent 31678ac commit aca9f79
Showing 1 changed file with 22 additions and 2 deletions.
24 changes: 22 additions & 2 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ function sync(dir, options = {}) {
}

function async(dir, options = {}) {
return new Promise(function(pResolve) {
return new Promise(function(pResolve, pReject) {
const paths = [];
if (options.resolvePaths) dir = resolve(dir);
const dirs = [dir];
Expand All @@ -35,7 +35,8 @@ function async(dir, options = {}) {
}
const dir = dirs[cursor];
if (options.includeDirs) paths[paths.length] = dir;
fs.readdir(dir, readdirOpts, function(_, dirents) {
fs.readdir(dir, readdirOpts, function(err, dirents) {
if (err) return pReject(getError(err, dir));
for (var j = 0; j < dirents.length; ++j) {
recurse(dirents[j], dir, paths, options, dirs);
}
Expand Down Expand Up @@ -75,6 +76,25 @@ function recurse(dirent, dir, paths, options, dirs) {
paths[paths.length] = fullPath;
}

function getError(error, path) {
let message = "";
switch (error.code) {
case "EACCES":
message = `You do not have permission to access "${path}".`;
break;
case "ENOENT":
message = `"${path}" does not exist or an invalid path was provided. Are you sure this is a valid directory?`;
break;
case "ENOTDIR":
message = `"${path}" is not a directory as expected. fdir only works with directories.`;
break;
}
return {
...error,
message: `${message}\nIf you think this is a bug, please open an issue at: https://github.com/thecodrr/fdir`
};
}

module.exports = {
sync,
async
Expand Down

0 comments on commit aca9f79

Please sign in to comment.