Lambda中如何获取MySQL连接错误日志?main与getData函数连接异常排查
AWS Lambda中mysql2连接池getData函数无法获取连接的问题分析与解决
问题原因
连接获取写法错误
mysql2的pool.getConnection()支持回调、Promise两种模式,你在getData函数中混用了两种模式:传入async conn => conn作为回调是错误的——回调模式的参数应为(error, connection),而非async函数。这种错误写法会导致Promise无法正确解析,最终返回Promise { <pending> }。未等待Promise执行完成
如果调用getData()时没有使用await,函数会直接返回pending状态的Promise,不会等待内部数据库操作完成,表现为仅显示Promise { }。空catch块吞掉错误
getData的catch块为空,所有数据库连接、查询错误都被静默处理,没有任何日志输出,导致无法排查问题。未释放连接
getData中获取连接后未调用connection.release(),会导致连接池连接被耗尽,后续请求无法获取新连接。
错误日志获取方法
- 补全错误捕获逻辑:在catch块中添加错误日志输出,Lambda日志会同步到CloudWatch Logs,前往对应函数的日志组即可查看:
catch (error) { console.error('getData数据库操作错误:', error); throw error; } - 开启mysql2调试日志:在连接池配置中添加
debug: true,会输出连接建立、查询过程的详细日志:const pool = mysql.createPool({ // 原有配置项 debug: true }) - 检查Lambda权限:确保Lambda执行角色拥有CloudWatch Logs的写入权限(
logs:CreateLogGroup、logs:CreateLogStream、logs:PutLogEvents),否则日志无法正常生成。
修正后的getData函数代码
async function getData() { let connection; try { // 使用Promise模式正确获取连接,无需传入回调 connection = await pool.getConnection(); const result = await connection.query(`你的SQL查询语句`); return result; } catch (error) { console.error('getData数据库错误:', error); throw error; // 抛出错误让调用者处理 } finally { // 无论成功失败,确保连接释放回池 if (connection) { connection.release(); } } }
调用注意事项
在main函数中调用getData时,必须使用await等待其执行完成:
module.exports.main = async (event) => { // ...其他逻辑 const dataResult = await getData(); // ...处理结果 }
内容的提问来源于stack exchange,提问作者RomeoHY
相关产品推荐
相关产品推荐

