使用 net.createConnection 保证 Node.js 错误处理

发布于 2024-12-06 03:05:27 字数 390 浏览 0 评论 0原文

我想知道 Node.js 是否能保证错误处理程序将捕获代码中的所有错误,如下所示:

var c = net.createConnection(port, host);
c.on('error', function (e) { ... });

我必须处理在调用 createConnection 和设置错误处理程序的语句,这有时会导致 createConnection 内部错误渗透到顶层(大概是因为这些错误有时发生在设置错误处理程序之前)。但除非我遗漏了一些东西,否则原则上这可能会发生在上面的代码中——只是不太可能。有没有什么方法可以真正保证 createConnection 中发生的所有错误都会传递给错误处理程序?

I was wondering if Node.js provides any guarantee that the error handler will catch all errors in code like the following:

var c = net.createConnection(port, host);
c.on('error', function (e) { ... });

I've had to deal with code where other statements intervened between the call to createConnection and the statement which sets the error handler, and this sometimes caused errors internal to createConnection to percolate to the top level (presumably because these errors sometimes occurred before the error handler had been set). But unless I'm missing something, this could in principle happen in the code above -- it's just not very likely. Is there any way of actually guaranteeing that all errors which occur within createConnection will get passed to the error handler?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

何以心动 2024-12-13 03:05:27

仅当节点存在错误时才会发生这种情况。

JavaScript 是单线程的,在附加事件处理程序和创建连接之间该过程通常不会中断。

该代码不会捕获 javascript 中生成的任何错误。

因此,如果节点中存在错误,则可能存在一些您的代码无法捕获的错误。如果您在后台运行了一些狡猾的低级代码,导致混乱,则可能会发生一些您的代码无法捕获的错误。

但在正常使用情况下,您的代码是“线程安全的”。您在发生任何错误之前绑定事件处理程序,因为您的代码是阻塞的并且没有任何东西可以引发错误。

It will only happen if there are bugs in node.

JavaScript is single threaded, the process will not normally be interrupted between attaching the event handler and creating the connection.

No error generated in javascript land will be uncaught by that code.

So if there was a bug in node, there could probably be some errors your code would not catch. If you had some dodgy low level code running in the background causing mayhem it could be possible that some errors would occur that your code would not catch.

But under normal usage, your code is "threadsafe". Your binding the event handler before any errors occur because your code is blocking and nothing can throw errors.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文