I have a subroutine in Node to load configuration etc before proper application starts. It turns out that in case file is not found, the exception fails to be catched and breaks the app.
Relevant code:
const fs = require('fs');
class FileParser {
static configure(filename) {
let file;
try {
file = this.loadFileSync(filename);
} catch (err) {
console.log(`File ${filename} not found`);
}
// ...
}
static loadFileSync(filename) {
fs.accessSync(filename, fs.F_OK);
return fs.readFileSync(filename, 'utf8');
}
}
If file is not found the fs.accessSync()
will throw an exception. Good, as it's there to safeguard fs.readFileSync()
. But I thought that this exception will propagate up through calling functions and can be catched there - hence the try...catch
in configure()
.
I don't want to resolve the exception in loadFileSync()
as it is used elsewhere and functions calling loadFileSync()
are to deal with the exception differently. So, what's the proper way to safeguard against file not found here and bubbling exceptions in general?
via Forseti
No comments:
Post a Comment