0

我在我的服务器上安装了 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/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

8000我在端口上运行node.jssocket.io和.node-mysqlmc

的文件路径events.js/node/lib/events.js.

如果我使用forever我可以连续运行它,但仍然会出现错误。它只是重新启动脚本。不是最好的解决方案(总比没有好,但可能是最差的解决方案)。

我会尝试uncaughtException但仍然不是最好的解决方案。这段代码:

process.on('uncaughtException', function (err) {
  console.log('Caught exception: ' + err);
});

如果可以的话,请帮助我。谢谢。

4

1 回答 1

1

您需要处理 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();

这是处理与https://github.com/felixge/node-mysql/blob/master/Readme.md#server-disconnects断开连接的示例:

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();
于 2013-08-08T01:47:51.777 回答