为什么Node.js停止工作?

时间:2013-08-07 22:15:54

标签: 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/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

我使用8000socket.ionode-mysql在端口mc上运行node.js.

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

如果我使用forever我可以连续运行它,但错误仍然存​​在。它只是重启脚本。不是最好的解决方案(总比没有好,但可能是最糟糕的解决方案)。

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

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

如果可以,请帮帮我。感谢。

1 个答案:

答案 0 :(得分: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();