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.
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).
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). Instead, I opted to just construct my errors as napi_value
types, and return these via napi_reject_deferred
. This seemed to have the desired effect, of being caught properly when doing a 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. 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
? Can you give a code example ?