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 :-)
You have to catch the error and then check what type of error it is.
Try using Async instead to avoid blocking the only thread you have with NodeJS. Check this example:
Later can use this async function with try/catch from any other function:
Happy Coding!
While the accepted solution is okay, I found a much better way of handling this. You can just check if the file exists synchronously:
Basically,
fs.readFileSync
throws an error when a file is not found. This error is from theError
prototype and thrown usingthrow
, hence the only way to catch is with atry / catch
block: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
code
property 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
message
property to verify the detailed error message, which in this case is:Hope this helps.
I use an immediately invoked lambda for these scenarios:
async
version: