gpt4 book ai didi

node.js - 为什么Node.js停止工作?

转载 作者:行者123 更新时间:2023-12-03 08:33:06 25 4
gpt4 key购买 nike

我在服务器上安装了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端口上使用 socket.ionode-mysqlmc运行node.js。
events.js的文件路径是 /node/lib/events.js

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

我将尝试 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();

这是处理与 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();

关于node.js - 为什么Node.js停止工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18114754/

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