I am using node-postgres to query my database and would like to know how to use async/await and handle errors correctly
An example of my use is here with a very simple query
const { Pool } = require('pg');
let config;
if (process.env.NODE_ENV === 'production' || process.env.NODE_ENV === 'staging') {
config = { connectionString: process.env.DATABASE_URL, ssl: true };
} else {
config = {
host: 'localhost',
user: 'myuser',
database: 'mydatabase',
};
}
const pool = new Pool(config);
async function getAllUsers() {
let response;
try {
response = await pool.query('select * FROM users');
} catch (error) {
throw error;
}
return response.rows;
}
Then in my routes.js
I have
app.get('/all_users', async (req, res) => {
const users = await queries.getAllUsers();
console.log(users); // returns all users fine
});
This is my understanding so far, but i don't think I am approaching this correctly as when it comes to errors my app will freeze and throw UnhandledPromiseRejectionWarning
. So if I provide an incorrect table for example
async function getAllUsers() {
let response;
try {
response = await pool.query('select * FROM notable');
} catch (error) {
throw error;
}
return response.rows;
}
UnhandledPromiseRejectionWarning: error: relation "notable" does not exist
The app will crash after 30 seconds and I have not handled this error gracefully. What am I missing?