I'm quite new to NodeJS, and I came across a construction that I can't wrap my head around. Consider the following code:
router.get("/", function(req, res, next) {
let db = new sqlite3.Database(dbname, sqlite3.OPEN_READONLY, (err) => {
if (err) next(err);
});
res.render("views/page");
}
If an exception is raised by Database
(for instance because dbname
does not exist), then the callback will pass it to the Express error handler (next
). But the code does not stop there, and it will continue to execute the next line and attempt to render
something, which is problematic if the error handler also sends headers. If I add a return
statement within the callback, it will simply terminate Database
but not the rest of the function.
My question: is there anyway to prevent the rest of the code from being executed if an exception is raised?
CodePudding user response:
Please read the sqlite3 npm documentation. Ideally, you should not be opening a database connection on every request. Instead, you should open the database connection when the server is started, and share a reference to the db
variable to be used in the API routes (gets/posts).
Unless you just want to make it work, I believe the below should do it.
router.get("/", function(req, res, next) {
let db = new sqlite3.Database(dbname, sqlite3.OPEN_READONLY, (err) => {
if (err) return next(err);
res.render("views/page");
});
}
EDIT: Javascript does not allow for async/await when instantiating objects, so in this case I believe would be better to just initialize the database connection outside the router method, like below, and use the error
event to handle errors
const db = new sqlite3.Database(dbname, sqlite3.OPEN_READONLY);
db.on('error', function(err) { /*handle error here*/ });
router.get("/", function(req, res, next) {
res.render("views/page");
});
}