I set up the following to handle queries to a SQLite database. When there are no errors with the query, it performs as expected and all rows are logged to the console.
When I test the functionality by adding a typo to the table name, I get an uncaught exception. I'm not sure why this is the case, and I thought that the exception would be handled by reject()
. I'm new to JS and not sure where I'm going wrong here. Any help appreciated.
const sqlite3 = require("sqlite3").verbose();
const dbPath = "db_path";
const db = new sqlite3.Database(dbPath);
const query = (command, method = "all") => {
return new Promise((resolve, reject) => {
db[method](command, (error, result) => {
if (error) {
reject(error);
} else {
resolve(result);
}
});
});
};
async function getResults() {
const results = await query("SELECT * FROM nonexistant_table");
console.log(results);
}
getResults();
This is the exception I'm getting:
node:internal/process/promises:391
triggerUncaughtException(err, true /* fromPromise */);
^
Error: SQLITE_ERROR: no such table: set_master1
--> in Database#all('SELECT * FROM set_master1', [Function (anonymous)])
at D:\test_folder\js_tutorial\main.js:7:15
at new Promise (<anonymous>)
at query (D:\test_folder\js_tutorial\main.js:6:10)
at getResults (D:\test_folder\js_tutorial\main.js:18:25)
at Object.<anonymous> (D:\test_folder\js_tutorial\main.js:21:1)
at Module._compile (node:internal/modules/cjs/loader:1469:14)
at Module._extensions..js (node:internal/modules/cjs/loader:1548:10)
at Module.load (node:internal/modules/cjs/loader:1288:32)
at Module._load (node:internal/modules/cjs/loader:1104:12) {
errno: 1,
code: 'SQLITE_ERROR',
__augmented: true
}
Node.js v20.18.0
Since there's no try-catch block around the await query(...) call in getResults, the rejection is not handled,
Your code should be
const sqlite3 = require("sqlite3").verbose();
const dbPath = "db_path";
const db = new sqlite3.Database(dbPath);
const query = (command, method = "all") => {
return new Promise((resolve, reject) => {
db[method](command, (error, result) => {
if (error) {
reject(error);
} else {
resolve(result);
}
});
});
};
async function getResults() {
try {
const results = await query("SELECT * FROM nonexistant_table");
console.log(results);
} catch (error) {
// Error is now caught and handled here
console.error("Error executing query:", error.message);
}
}
getResults();