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.readFileSyncthrows an error when a file is not found. This error is from theErrorprototype and thrown usingthrow, hence the only way to catch is with atry / catchblock:Unfortunately you can not detect which error has been thrown just by looking at its prototype chain:
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
codeproperty and check its value:This way, you deal only with this specific error and re-throw all other errors.
Alternatively, you can also access the error’s
messageproperty to verify the detailed error message, which in this case is: