为什么Node.js停止工作?
我在我的服务器上安装了node.js,它正在工作。但它会在一段时间后停止,并出现以下错误:为什么Node.js停止工作?,node.js,error-handling,Node.js,Error Handling,我在我的服务器上安装了node.js,它正在工作。但它会在一段时间后停止,并出现以下错误: events.js:77 throw er; // Unhandled 'error' event ^ Error: Connection lost: The server closed the connection. at Protocol.end (/var/www/node/node_modules/mysql/lib/protocol/Proto
events.js:77
throw er; // Unhandled 'error' event
^
Error: Connection lost: The server closed the connection.
at Protocol.end (/var/www/node/node_modules/mysql/lib/protocol/Protocol.js:73:13)
at Socket.onend (stream.js:79:10)
at Socket.EventEmitter.emit (events.js:122:20)
at _stream_readable.js:910:16
at process._tickCallback (node.js:373:11)
error: Forever detected script exited with code: 8
error: Forever restarting script for 14 time
我使用socket.io
、node mysql
和mc
在端口8000
上运行node.js
events.js
的文件路径是/node/lib/events.js
如果我永远使用
,我可以连续运行它,但仍然会出现错误。只需重新启动脚本。不是最好的解决方案(总比没有好,但可能是最坏的解决方案)
我想尝试一下uncaughtException
,但仍然不是最好的解决方案。此代码:
process.on('uncaughtException', function (err) {
console.log('Caught exception: ' + err);
});
如果可以的话,请帮助我。谢谢。您需要处理mysql连接上的错误事件。如果事件发射器发出“错误”事件而未处理,则会引发异常。我不确定您在代码中做了什么,但请参见下文了解您应该如何处理此问题:
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'localhost',
user : 'me',
password : 'secret',
});
connection.on('error', function (err) {
// Handle your error here.
});
connection.connect();
connection.query('SELECT 1 + 1 AS solution', function(err, rows, fields) {
if (err) throw err;
console.log('The solution is: ', rows[0].solution);
});
connection.end();
以下是一个处理以下断开连接的示例:
它的意思就是它所说的。您连接的MySQL服务器关闭了应用程序打开的连接。错误是因为它是意外的。这可能意味着您试图让连接打开的时间过长,服务器最终认为它已超时。但是,很难说没有看到代码。如果您正在使用,请确保最终使用了
connection.end()
。感谢Jonathan的回复。我不知道,连接丢失
实际上是与数据库的连接丢失。谢谢你的回复。或多或少这就是我要找的。加上这个代码。如果你更新你的答案,我会接受。
function handleDisconnect() {
connection = mysql.createConnection(db_config); // Recreate the connection, since
// the old one cannot be reused.
connection.connect(function(err) { // The server is either down
if(err) { // or restarting (takes a while sometimes).
console.log('error when connecting to db:', err);
setTimeout(handleDisconnect, 2000); // We introduce a delay before attempting to reconnect,
} // to avoid a hot loop, and to allow our node script to
}); // process asynchronous requests in the meantime.
// If you're also serving http, display a 503 error.
connection.on('error', function(err) {
console.log('db error', err);
if(err.code === 'PROTOCOL_CONNECTION_LOST') { // Connection to the MySQL server is usually
handleDisconnect(); // lost due to either server restart, or a
} else { // connnection idle timeout (the wait_timeout
throw err; // server variable configures this)
});
}
handleDisconnect();