gpt4 book ai didi

mysql - ECONNRESET 错误导致 NodeJS 应用程序崩溃

转载 作者:行者123 更新时间:2023-12-05 02:52:57 25 4
gpt4 key购买 nike

我是编码的新手,我需要一些帮助来解决我遇到的一个错误。

我正在运行一个 NodeJS 应用程序(一个 Discord.js 机器人),我的机器人具有在用户键入特定命令时将用户 ID 注册到 MySQL 数据库的功能。有时它工作得很好,但有时它会因 ECONNRESET 错误而崩溃:

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

Error: read ECONNRESET
at TCP.onStreamRead (internal/stream_base_commons.js:205:27)
Emitted 'error' event on Connection instance at:
at Connection._handleProtocolError (C:\Users\Celeron\Desktop\DiscordBot\node_modules\mysql\lib\Connection.js:423:8)
at Protocol.emit (events.js:315:20)
at Protocol._delegateError (C:\Users\Celeron\Desktop\DiscordBot\node_modules\mysql\lib\protocol\Protocol.js:398:10)
at Protocol.handleNetworkError (C:\Users\Celeron\Desktop\DiscordBot\node_modules\mysql\lib\protocol\Protocol.js:371:10)
at Connection._handleNetworkError (C:\Users\Celeron\Desktop\DiscordBot\node_modules\mysql\lib\Connection.js:418:18)
at Socket.emit (events.js:315:20)
at emitErrorNT (internal/streams/destroy.js:92:8)
at emitErrorAndCloseNT (internal/streams/destroy.js:60:3)
at processTicksAndRejections (internal/process/task_queues.js:84:21) {
errno: 'ECONNRESET',
code: 'ECONNRESET',
syscall: 'read',
fatal: true
}

最佳答案

首先,您应该捕获错误,这样您的应用程序就可以正确处理它,并且当 mysql 连接因任何奇怪的原因关闭时不会崩溃。尝试使用 connection.on('error', ...)try-catch blocks .

为了保持打开的连接,您应该在关闭时重新连接。或者简单地使用 mysql 的 pooling connection ,只需更改一次代码即可很好地处理自动重新连接。

PS:合并多个连接对于异步应用程序(如服务器)来说通常是个好主意,但通过合并(connectionLimit : 1)维护单个连接是安全的,只是为了自动重新连接本身。

PPS: Mysql的不活动超时可以在服务器的my.cnf

中配置

关于mysql - ECONNRESET 错误导致 NodeJS 应用程序崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62416274/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com