[英]What does `napi_throw_error` do when called from an asynchronous N-API addon's `napi_async_complete_callback`?
I recently completed making an asynchronous version for all the functions in a pure C API, wrapped with N-API to work with JS/TS as a nodejs addon.我最近完成了为纯 C API 中的所有函数制作异步版本,并使用 N-API 包装以与 JS/TS 作为 nodejs 插件一起使用。
The last problem I had to fix was making sure that C POSIX-style errors (ie, returned integer codes) were transferred correctly to the JS at the end of a worker's execution (with the corresponding string, for which we have both an enum of exceptions, and a list of error messages).我必须解决的最后一个问题是确保在工人执行结束时将 C POSIX 样式错误(即返回的 integer 代码)正确传输到 JS(使用相应的字符串,我们都有一个枚举异常和错误消息列表)。
When thrown with napi_throw_error
(as I did for the synchronous version of all our calls), within the napi_async_complete_callback
, these exceptions were never caught at the JS level (I suppose it was because it was within a different async context; I saw online people having a similar problem with ajax).当使用
napi_throw_error
抛出时(就像我对所有调用的同步版本所做的那样),在napi_async_complete_callback
内,这些异常从未在 JS 级别被捕获(我想这是因为它在不同的异步上下文中;我看到网上的人有ajax 的类似问题)。 Instead, I opted to just construct my errors as napi_value
types, and return these via napi_reject_deferred
.相反,我选择将我的错误构造为
napi_value
类型,并通过napi_reject_deferred
返回这些错误。 This seemed to have the desired effect, of being caught properly when doing a try { await My_NapiWrapper_XYZ() } catch (ex) {... }
.这似乎具有预期的效果,即在执行
try { await My_NapiWrapper_XYZ() } catch (ex) {... }
时被正确捕获。
So I don't really have a problem to fix, but I AM intrigued.所以我真的没有要解决的问题,但我很感兴趣。 These
napi_throw_error
thrown errors do probably go somewhere .这些
napi_throw_error
抛出的错误可能是 go某处。 Though I have no idea where.虽然我不知道在哪里。 Where should one look to catch an error thrown with
napi_throw_error
from a napi_async_complete_callback
?应该从哪里捕捉
napi_throw_error
中napi_async_complete_callback
引发的错误? Can you give a code example?你能给出一个代码示例吗?
No, they don't go anywhere.不,他们不在任何地方 go 。 It is a bug that I just opened with them:
这是我刚刚与他们一起打开的错误:
https://github.com/nodejs/node/issues/41377 https://github.com/nodejs/node/issues/41377
There is a general problem with handling exceptions in asynchronous callbacks.在异步回调中处理异常存在一个普遍问题。 Normally, they cannot be catched and should lead to program termination but Node's developers have decided to try to keep it running when they can.
通常,它们无法被捕获并会导致程序终止,但 Node 的开发人员已决定尽可能保持其运行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.