1

我在 AWS Lambda 上使用 Node.js mysql2 库时遇到了一个奇怪的错误。

我正在我的 AWS Lambda 函数中连接到 AWS Aurora 上的 mysql 数据库。

const conn = mysql.createConnection({
    host: '',
    port: 3306,
    user: '',
    password: '',
    database: ''
  })

  const query = util.promisify(conn.query).bind(conn)

我查询

try {
  const result = await query(queryString)
  if (result && result.length > 0) {
    id = result[0].id
  }
} catch (error) {
  console.log('ERROR: query error')
  console.log(error)
}

这一直工作得很好。

这个特定的 AWS Lambda 函数由 Webhook 通过 API Gateway 调用。

只有当 webhook 调用该函数时,我才会收到此错误消息,说明 mysql 连接在查询之前已关闭。

无论在哪里调用 connection.end() 或 connection.close(),查询之前都没有任何意义。

当使用与webhook 传递的相同主体从 PostMan 调用该函数时,该函数可以很好地通过查询。连接没有关闭!

API Gateway 的 AWS Lamba 事件中是否存在可能导致连接中断的内容?为什么 node.js mysql2 只有在 webhook 请求的情况下才会抛出这个错误?

要完成 AWS Lambda 日志错误是:

ERROR   Uncaught Exception  
{
    "errorType": "Error",
    "errorMessage": "write after end",
    "code": "ERR_STREAM_WRITE_AFTER_END",
    "fatal": true,
    "stack": [
        "Error [ERR_STREAM_WRITE_AFTER_END]: write after end",
        "    at writeAfterEnd (_stream_writable.js:266:14)",
        "    at Socket.Writable.write (_stream_writable.js:315:5)",
        "    at Connection.write (/var/task/node_modules/mysql2/lib/connection.js:217:17)",
        "    at Connection.writePacket (/var/task/node_modules/mysql2/lib/connection.js:262:12)",
        "    at ClientHandshake.sendCredentials (/var/task/node_modules/mysql2/lib/commands/client_handshake.js:63:16)",
        "    at ClientHandshake.handshakeInit (/var/task/node_modules/mysql2/lib/commands/client_handshake.js:136:12)",
        "    at ClientHandshake.execute (/var/task/node_modules/mysql2/lib/commands/command.js:39:22)",
        "    at Connection.handlePacket (/var/task/node_modules/mysql2/lib/connection.js:408:32)",
        "    at PacketParser.onPacket (/var/task/node_modules/mysql2/lib/connection.js:70:12)",
        "    at PacketParser.executeStart (/var/task/node_modules/mysql2/lib/packet_parser.js:75:16)"
    ]
}

除此之外,查询位于 try catch 块内,但 AWS Lambda 显示“未捕获的异常”

感谢您的帮助,亚历克斯

4

0 回答 0