在 nodejs 中,我们可以处理这样的异常:
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.');
deno 的替代方案是什么?我知道有 window.onunload ,但它不处理错误
最佳答案
Deno 总是死于未捕获的异常,这是一个设计选择(实际上是一个核心选择)。您不能为您的错误放置全局处理程序,因为有时您的异常可能是不可恢复的,并且可能会导致改变应用程序整体状态的副作用,总而言之,未处理的异常处理程序意味着问题。到目前为止,NodeJS 不鼓励对异常进行全局处理,因此请不要在将来在该平台上依赖此类代码。
话虽如此,如何处理拒绝? try
/catch
/finally
用于同步代码。 .then
/.catch
/.finally
对于异步代码。
编辑:您可以使用的一个有趣的资源是 unhandledRejection
事件,它是一个用于实现各种清理的事件,意味着关闭打开的连接、释放资源、关闭文件等。这不会阻止异常终止程序,但会给你空间来防止对程序终止的次要影响。
https://developer.mozilla.org/en-US/docs/Web/API/Window/unhandledrejection_event
关于node.js - Deno:如何处理异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64871554/