gpt4 book ai didi

node.js - 始终在Node.js中处理错误

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

我想在node.js退出之前使用任何退出代码运行任何重要代码,或者始终使用任何守护程序(例如pm2,永远)重新启动它。但是代码不是同步的,所以这里是问题。像下面这样的处理程序是否足够?

process.stdin.resume();

//Won't use because it can only run synchronous code.
process.on("exit", code => console.log("Process has exited with code "+code));
process.on("SIGINT", err => exit_handler(err, "SIGINT"));
process.on("SIGUSR1", err => exit_handler(err, "SIGUSR1"));
process.on("SIGUSR2", err => exit_handler(err, "SIGUSR2"));
process.on("unhandledRejection", err => exit_handler(err, "unhandledRejection"));

function exit_handler(err, type)
{
//handle error, run code.
if (err) console.error(err.stack);
process.exit();
}

有问题的 events

最佳答案

我还建议添加:

process.on('uncaughtException', err => exit_handler(err, "uncaughtException"));

我会担心完全依赖这些处理程序,但是,我建议您使用Forever之类的东西: https://github.com/foreverjs/forever来监视脚本。我不确定是否可以让Forever在退出时运行脚本,但是如果退出,它将重新启动脚本,这可能是此时您需要执行的任何操作的机会。还有Upstart和Monit,它们的功能相似。

整理一个测试脚本来很好地完成所有这些工作,例如
"Use strict";

var fs = require('fs');

process.stdin.resume();

var promise1 = new Promise((resolve) => {
setTimeout(resolve, 30000);
});

//Won't use because it can only run synchronous code.
process.on("exit", code => console.log("Process has exited with code "+code));
process.on("SIGINT", err => exit_handler(err, "SIGINT"));
process.on("SIGUSR1", err => exit_handler(err, "SIGUSR1"));
process.on("SIGUSR2", err => exit_handler(err, "SIGUSR2"));
process.on("unhandledRejection", err => exit_handler(err, "unhandledRejection"));
process.on('uncaughtException', err => exit_handler(err, "uncaughtException"));

function exit_handler(err, type)
{
//handle error, run code.
if (err) console.error("exit_handler: " + err.stack);
process.exit();
}

function testError()
{

fs.readFile('some file that doesnt exist.txt', function (err, data) {
if (err) throw err;
});
}

// Deliberately cause an error.
setTimeout (testError, 1000);


console.log('Waiting..');
promise1.then(() => {
console.log('Exiting');
});

关于node.js - 始终在Node.js中处理错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48805303/

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