我正在使用 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 秒后崩溃,我没有妥善处理此错误。我错过了什么?
最佳答案
当 async
函数或 Promise
抛出 Uncaught Error 时,或者当 catcher 也抛出时,例如您的
throw error;
这意味着函数的调用者将面临被拒绝的 Promise 需要处理。如果您在调用方中使用 await
,那么您还必须在调用方中使用 try/catch
才能正确捕获错误:
app.get('/all_users', async (req, res) => {
try {
const users = await queries.getAllUsers();
console.log(users);
} catch(e) {
// handle errors
}
});
无需在消费者中使用 try/catch
即可解决错误的另一种方法是不在 catch
中throw
错误:
async function getAllUsers() {
let response;
try {
response = await pool.query('select * FROM users');
return response.rows;
} catch (error) {
// handle error
// do not throw anything
}
}
但这会使消费者更难知道何时出现错误。
在这种特殊情况下,async
/await
/try
/catch
结构添加了很多语法没有太多好处的噪声 IMO - 目前,您可以考虑使用普通的 Promises:
const getAllUsers = () => pool.query('select * FROM users')
.then(response => response.rows);
// and:
app.get('/all_users', (req, res) => {
queries.getAllUsers()
.then((users) => {
console.log(users);
})
.catch((err) => {
// handle errors
});
});
async
和 await
当您有一些 .then
时您希望在您的代码中看起来更平坦。如果只有一个 .then
,IMO 将其转换为 async
/await
语法没有太大好处。当然,这取决于您。
关于node.js - 将 Async/Await 与 node-postgres 一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53910835/