feat(napi): keep stack traces in a deferred context #1637
Merged
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Currently, stack traces from the calling javascript context are not preserved, when an error is thrown inside a deferred context (e.g. an
async fn
). Thus, errors thrown inside async functions always look like this:Which is not very useful when debugging an application.
Current solution
The npm package trace can be used to add the stack traces to the errors thrown in another thread.
Proposal
This comment shows how stack traces can be added to errors thrown inside a deferred context: nodejs/node-addon-api#595 (comment)
Basically, for the stack trace to be preserved, an error needs to be created in the main thread, so the v8 can keep a reference to the calling function. As the error doesn't contain the error message of an error thrown inside the deferred context, the message and status code must be replaced in the error before returning the error back to the javascript process.
This PR adds this functionality as an optional feature, as creating a new error every time a promise is returned to the javascript process seems wasteful. I did some simple performance tests and the performance impact didn't seem to bad (the compute times seemed to be pretty much unchanged, but I think keeping this as an optional feature would be better).
With this feature enabled, stack traces from errors returned by a promise look like this:
This feature was originally requested here: MarkusJx/node-java-bridge#77