# Promise Error Handling Hooks: Rough Spec Algorithm ## ECMAScript/V8 algorithm ### General modifications All promises need to get a unique promise ID of some sort, e.g. a string or number. These can be created lazily if that is easier. All promises get a "rejection status" field, which is one of: "nothing"; "notified of rejection"; ".then'd" ### Modification to PromiseReject If a promise is rejected (which currently always goes through PromiseReject, both in the spec and in V8), and its rejection status is not ".then'd", send a message to the host environment consisting of "potentially unhandled rejection: (the promise ID, the rejection reason)", and set its rejection status to "notified of rejection." ### Modification to Promise.prototype.then If the promise's rejection status is "notified of rejection," send a message to the host environment consisting of "rejection handled: (the promise ID)". Set the promise's rejection status to ".then'd". ## Host environment algorithm The host environment has a list of outstanding rejected promise IDs and about-to-be-notified rejected promise IDs. Receive "potentially unhandled rejection" messages, and: - Add the given promise ID to the list of about-to-be-notified rejected promise IDs. - Queue a notify-rejected task, with parameters promise ID and rejection reason. Receive "rejection handled" messages, and: - Remove the given promise ID from the list of about-to-be-notified rejected promise IDs, if present. - If the given promise ID is in the list of outstanding rejected promise IDs, notify the user (via devtools and the onrejectionhandled event) that the rejection was handled. - (Note that only one of these two alternatives should ever occur.) The notify-rejected task, which is given a promise ID and rejection reason, does the following: - If the promise ID is no longer in the list of about-to-be-notified rejected promise IDs, do nothing. - Otherwise, - Notify about a rejection with the given promise ID and rejection reason. - Add the given promise ID to the list of outstanding rejected promise IDs.