{ -6ren">
gpt4 book ai didi

javascript - 即使处理了未捕获的异常,Node.js 程序也会退出

转载 作者:行者123 更新时间:2023-11-30 19:27:09 25 4
gpt4 key购买 nike

我编写了以下代码来处理我的应用程序中未捕获的异常(我知道这是一个相当幼稚的错误处理方法,代码只是为了问题的目的):

process.on("uncaughtException", err => {
console.log('Handling exception');
});

console.log('starting...');

function f() {
throw(new Error('Error'));
}

f();
console.log('Done');

当我运行代码时,我得到了以下输出:

starting...
Handling exception

由于某些原因,即使处理了异常,程序也没有运行最后一行代码就退出了。当我用 try-catch block 包装对 f() 的调用时,最后一行被执行并且“完成”一词被打印到屏幕上。

我的问题是:

  1. 这是预期的行为吗?
  2. 为什么这两种机制(监听事件和使用 try-catch)之间存在差异?

最佳答案

这正是您所期望的行为,未捕获的异常将停止脚本的正常执行,因此永远不会进行“完成”日志调用。

您可以在此处的 Node.js 文档中看到一个更好的示例:https://nodejs.org/api/process.html#process_event_uncaughtexception

正如文档所说:

Note that 'uncaughtException' is a crude mechanism for exception handling intended to be used only as a last resort.

They explicitly log "This will not run" as this is the expected behaviour.

If you do catch the exception the script execution will not stop and the log call will be made as normal.

process.on('uncaughtException', (err, origin) => {
fs.writeSync(
process.stderr.fd,
`Caught exception: ${err}\n` +
`Exception origin: ${origin}`
);
});

setTimeout(() => {
console.log('This will still run.');
}, 500);

// Intentionally cause an exception, but don't catch it.
nonexistentFunc();
console.log('This will not run.');

uncaughtException 处理程序旨在执行此操作:在您自己的代码中捕获 try ... catch 处理程序未处理的任何异常。主要目的应该是记录错误,以便日后修复。

在任何情况下,最好将脚本包装在像 Forever 这样的重启机制中,或者在发生这种情况时启动一个新的 Docker 容器。

现在在您的情况下没有真正的区别,因为脚本无论如何都会立即退出。但是看看这两个脚本之间的区别:

脚本 1:

// Keep the script alive by setting a timeout. Because we have an exception handler in place we can keep doing stuff!
let interval = setInterval(() => console.log("I'm still alive!!"), 500);
setTimeout(() => { clearInterval(interval); console.log("Timeout done...")} , 5000);

process.on("uncaughtException", err => {
console.log('Handling exception');
});

console.log('starting...');

function f() {
throw(new Error('Error'));
}

f();

console.log('Done');

脚本 2:

// Keep the script alive by setting a timeout. Since there is no exception handler set the script will terminate immediately in any case.

let interval = setInterval(() => console.log("I'm still alive!!"), 500);
setTimeout(() => { clearInterval(interval); console.log("Timeout done...")} , 5000);

console.log('starting...');

function f() {
throw(new Error('Error'));
}

f();

console.log('Done');

您可以在第二个脚本中看到我们直接退出,因为我们没有未捕获的异常处理程序。

关于javascript - 即使处理了未捕获的异常,Node.js 程序也会退出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56789610/

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