我正在使用 node-postgres 查询数据库,想知道如何使用 async/await 并正确处理错误。
这是我的一个使用示例,其中包含一个非常简单的查询:
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;
}
然后在我的routes.js
文件中,我有以下内容:
app.get('/all_users', async (req, res) => {
const users = await queries.getAllUsers();
console.log(users); // returns all users fine
});
这是我目前的理解,但我认为我处理不正确,因为当出现错误时,我的应用程序将会冻结并抛出UnhandledPromiseRejectionWarning
。例如,如果我提供了错误的表格。
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
这款应用程序将在30秒后崩溃,而我没有优雅地处理这个错误。我错过了什么?