NodeJS 连接 MySQL 出现 Connection lost: The server closed the connection

2026-03-06 39 浏览 0 评论

用 NodeJS 写了个爬虫,每运行一段时间就会出现 Connection lost: The server closed the connection:

events.js:292
      throw er; // Unhandled 'error' event
      ^

Error: Connection lost: The server closed the connection.
    at Protocol.end (D:\www\webspider\node_modules\mysql\lib\protocol\Protocol.j
s:112:13)
    at Socket. (D:\www\webspider\node_modules\mysql\lib\Connection.js
:94:28)
    at Socket. (D:\www\webspider\node_modules\mysql\lib\Connection.js
:526:10)
    at Socket.emit (events.js:327:22)
    at endReadableNT (internal/streams/readable.js:1327:12)
    at processTicksAndRejections (internal/process/task_queues.js:80:21)
Emitted 'error' event on Connection instance at:
    at Connection._handleProtocolError (D:\www\webspider\node_modules\mysql\lib\
Connection.js:423:8)
    at Protocol.emit (events.js:315:20)
    at Protocol._delegateError (D:\www\webspider\node_modules\mysql\lib\protocol
\Protocol.js:398:10)

感觉是数据库连接超时了,连接句柄上有一个监听错误的事件:

connection.on('error', function(err) {
  console.log(err.code); // 'ER_BAD_DB_ERROR'
});

connection.query('USE name_of_db_that_does_not_exist');

应该会像 Socket 一样,在出现错误的时候再重新连接。

但是最终我并没有这么做,我使用 pm2 启动应用,然后再这里错误的时候直接 progress.exit() 退出脚本,然后 pm2 会自动重新启动,这样感觉比较省事!


发布评论

发布评论前请先 登录
取消
0 评论
点赞
收藏

评论列表 0

暂无评论