Within node.js readFile() shows how to capture an error, however there is no comment for the readFileSync() function regarding error handling. As such, if I try to use readFileSync() when there is no file, I get the error Error: ENOENT, no such file or directory.
How do I capture the exception being thrown? The doco doesn't state what exceptions are thrown, so I don't know what exceptions I need to catch. I should note that I don't like generic 'catch every single possible exception' style of try/catch statements. In this case I wish to catch the specific exception that occurs when the file doesn't exist and I attempt to perform the readFileSync.
Please note that I'm performing sync functions only on start up before serving connection attempts, so comments that I shouldn't be using sync functions are not required :-)
Basically, fs.readFileSync throws an error when a file is not found. This error is an instance of the Error class and thrown using throw, hence the only way to catch is with a try / catch block:
var data;
try {
data = fs.readFileSync('foo.bar');
} catch (e) {
// Here you get the error when the file was not found,
// but you also get any other error
}
Unfortunately you can not detect which error has been thrown just by looking at its "class":
if (e instanceof Error)
is the best you can do, and this will be true for most (if not all) errors. Hence I'd suggest you go with the code property and check its value:
if (e.code === 'ENOENT') {
console.log('File not found!');
} else {
throw e;
}
This way, you deal only with this specific error and re-throw all other errors.
Alternatively, you can also access the error's message property to verify the detailed error message, which in this case is:
ENOENT, no such file or directory 'foo.bar'
Hope this helps.
You have to catch the error and then check what type of error it is.
try {
var data = fs.readFileSync(...)
} catch (err) {
// If the type is not what you want, then just throw the error again.
if (err.code !== 'ENOENT') throw err;
// Handle a file-not-found error
}