node.jsbetter-sqlite3

How do I handle errors when a row does not exist, using better-sqlite3?


how do I handle the error that happens whenever you try to use .prepare(#).get() and the query does not exist?

let businessType = DB.prepare(`SELECT businessType from 'Profiles' WHERE userId = '${author.id}'`).get().businessType;

so basically how do I stop crashes whenever "businessType" does not exist and rather than the script crashing I can just send a message like "User does not exist" or something.

Thanks in advance!


Solution

  • get() will return undefined if the row doesn't exist.

    You will need to check your response before trying to extract the data.

    const row = DB.prepare(`SELECT businessType from 'Profiles' WHERE userId = ?`).get(author.id);
    if(row) {
      // profile recorded exist
      ...
    } else {
      // profile doesn't exist.
      ...
    }