hardfork
hardfork

Reputation: 3261

Check for error during database query and return it in an asynchronous call in express

I'm using the npm modules sqlite3.

If someone opens my site, I want 2 sqlite-queries to be executed. If an error occurs in the first or second query, I want the express-application to answer with a 404-status-code and some text.

The problem: I can't return out of the whole thing. If there are errors in the first and second query, both res.status(404).end will be executed. And trying to call end() 2 times will crash the application.

router.get("/", (req, res) => {
  //...
  db.serialize(() => {
    db.run("INSERT INTO modul...", (err) => {
      if (err) { res.status(404).end("An error occured during insertion"); return; }
    });

    db.get("SELECT * FROM modul...", (err, row) => {
      if (err) { res.status(404).end("An error occured during selection"); return; }
      res.json({ module: row });
    });
  });
});

I know that I'm in an asynchronous call and it doesn't work because of that but I don't know how to solve this issue.

Upvotes: 0

Views: 60

Answers (2)

Terry Lennox
Terry Lennox

Reputation: 30695

You can check for the initial error and skip running the second if this occurs:

router.get("/", (req, res) => {
    db.serialize(() => {
        db.run("INSERT INTO modul...", (err) => {
            if (err) { 
                res.status(404).end("An error occured during insertion"); 
            } else {
                db.get("SELECT * FROM modul...", (err, row) => {
                    if (err) { res.status(404).end("An error occured during selection"); return; }
                    res.json({ module: row });
                });
            }
        });
    });
});

Upvotes: 1

agtabesh
agtabesh

Reputation: 568

Please take a look at this code:

router.get("/", async (req, res) => {
  //...
  return db.serialize(async () => {
    try {
        await db.run("INSERT INTO modul...");
        const row = await db.get("SELECT * FROM modul...");
        return res.json({ module: row });
    } catch (e) {
        return res.status(404).end("An error occured during insertion");
    }
  });
});

Upvotes: 0

Related Questions