问题描述
我对编码有点陌生,我需要一些帮助来解决我遇到的一个错误.
I am kind of new to coding and I needed some help with one error that I'm getting.
我正在运行一个 NodeJS 应用程序(一个 Discord.js 机器人),我的机器人具有在用户键入某个命令时将用户 ID 注册到 MySQL 数据库的功能.有时它工作得很好,但有时它会因 ECONNRESET
错误而崩溃:
I'm running a NodeJS application (a Discord.js bot), my bot has the function to register a user's ID to a MySQL database when the user types a certain command. Sometimes it works just fine, but other times it crashes with an ECONNRESET
error:
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:UsersCeleronDesktopDiscordBot
ode_modulesmysqllibConnection.js:423:8)
at Protocol.emit (events.js:315:20)
at Protocol._delegateError (C:UsersCeleronDesktopDiscordBot
ode_modulesmysqllibprotocolProtocol.js:398:10)
at Protocol.handleNetworkError (C:UsersCeleronDesktopDiscordBot
ode_modulesmysqllibprotocolProtocol.js:371:10)
at Connection._handleNetworkError (C:UsersCeleronDesktopDiscordBot
ode_modulesmysqllibConnection.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
}
推荐答案
首先,你应该catch
错误,这样你的应用程序才能正确处理它并且不会在mysql连接时崩溃因任何奇怪的原因关闭.尝试使用 connection.on('error', ...)
或 try-catch 块.
First of all, you should catch
the error, so you app can handle it properly and doesn't crash when mysql connection is closed for any odd reason. Try either with connection.on('error', ...)
or with try-catch blocks.
为了保持打开的连接,您应该在关闭时重新连接.或者干脆使用mysql的pooling connection,很好的处理自动重连,单个代码更改.
For keeping an open connection, you should either reconnect on close. Or simply use mysql's pooling connection, which handles automatic reconnection very well, with a single code change.
PS:对于异步应用程序(如服务器)来说,池化多个连接通常是一个好主意,但通过池化(connectionLimit : 1
)维护单个连接是安全的,仅用于自动重新连接本身.
PS: Pooling multiple connections is a generally good idea for async apps, like servers, but it's safe to maintain a single connection via pooling (connectionLimit : 1
) just for automatic reconnection itself.
PPS:Mysql的不活动超时可以在服务器的my.cnf
PPS: Mysql's inactivity timeout can be configured in server's my.cnf
这篇关于ECONNRESET 错误导致 NodeJS 应用程序崩溃的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!