Was wondering the same thing and came across this question.
Apparently Sentry is using an AsyncLocalStorage based on the Node's async_hooks API. (on previous versions, the Domain API was used).
I'm sure someone smarter than me can give a more detailed explanation but from what I understood this API allows you to get the ID of the current execution context (which would be the callback passed to the withScope
method in your example). Internally Sentry will then associate this newly created scope with the execution context's ID. Now, when captureException
is called within the same execution context, Sentry can use the ID to look up the scope automatically without you having to explicitely pass it to that method.