在 javascript 异步错误处理中,async 函数捕获数据库操作错误的标准做法是使用 try...catch 语句包裹 await 表达式。当数据库操作(如查询或连接)抛出异常时,await 会暂停执行并将错误传递给 catch 块,开发者可以在其中进行日志记录、重试或返回特定状态码。若未使用 try...catch,未处理的 promise 拒绝会导致程序崩溃或触发 unhandledrejection 事件。

try...catch 如何拦截数据库查询异常
try...catch 是同步和异步代码中处理错误的核心结构。在 async 函数中,await 关键字用于等待 Promise 解决。如果 Promise 被拒绝(例如数据库连接失败或 SQL 语法错误),await 会立即抛出该错误,导致代码跳转到 catch 块。这种机制允许开发者集中处理所有可能的数据库错误,而不是在每个回调中单独处理。

const mysql = require('mysql2/promise');
async function getUserById(userId) {
const connection = await mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'password',
database: 'test_db'
});
try {
const [rows] = await connection.execute(
'SELECT * FROM users WHERE id = ?',
[userId]
);
if (rows.length === 0) {
return { error: 'User not found' };
}
return rows[0];
} catch (error) {
console.error('Database query failed:', error.message);
throw new Error('Failed to fetch user data');
} finally {
await connection.end();
}
}
getUserById(1).then(console.log).catch(console.error); // 输出: Database query failed: ...
上述代码展示了完整的数据库操作流程。首先创建连接,然后在 try 块中执行查询。如果查询成功,返回用户数据;如果失败,catch 块捕获错误并记录日志。finally 块确保连接关闭,无论是否发生错误。调用 getUserById 时,如果数据库不可用,错误会被正确捕获并打印。
全局错误处理器如何处理未捕获的数据库错误
除了局部的 try...catch,Node.js 提供了全局错误处理器来应对未捕获的 Promise 拒绝。通过监听 unhandledRejection 事件,可以捕获那些未被 try...catch 包裹的 async 函数中的错误。这对于防止应用程序因意外错误而崩溃至关重要。

process.on('unhandledRejection', (reason, promise) => {
console.error('Unhandled Rejection at:', promise, 'reason:', reason);
});
async function riskyDbOperation() {
// 模拟一个未处理的错误
throw new Error('This error is not caught locally');
}
riskyDbOperation(); // 触发 unhandledRejection 事件
这段代码注册了一个全局处理器,当 riskyDbOperation 抛出未捕获的错误时,控制台会输出详细的错误信息。这有助于在开发阶段发现潜在问题。在生产环境中,还可以将错误发送到监控服务,以便及时响应。
数据库连接池满时 async 函数的行为表现
当数据库连接池达到最大容量时,新的数据库请求会进入等待队列或直接失败,具体取决于数据库驱动的实现。在 async 函数中,如果 await 等待的连接获取超时,会抛出超时错误。开发者需要设置合理的超时时间,并在 catch 块中处理这种情况,以避免长时间阻塞。
const pool = mysql.createPool({
host: 'localhost',
user: 'root',
password: 'password',
database: 'test_db',
waitForConnections: true,
connectionLimit: 10,
queueLimit: 0
});
async function handleConcurrentRequests() {
for (let i = 0; i {
try {
const connection = await pool.getConnection();
try {
await connection.execute('SELECT SLEEP(5)');
console.log(`Request ${i} completed`);
} finally {
connection.release();
}
} catch (error) {
console.error(`Request ${i} failed:`, error.message);
}
}, i * 100);
}
}
handleConcurrentRequests();
此示例模拟了高并发场景。由于连接池限制为 10,超过 10 的请求会等待。如果等待时间过长,可能会触发超时错误。通过 catch 块捕获这些错误,可以确保程序不会因连接池满而完全停止。实际运行中,部分请求会成功,部分会因超时或队列限制而失败,具体结果取决于系统负载和配置。
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南











