Skip to content

Instantly share code, notes, and snippets.

@Jack-Works
Last active June 7, 2020 05:07
Show Gist options
  • Save Jack-Works/3ba26cb0326897ad9bdd64b70f7d5b98 to your computer and use it in GitHub Desktop.
Save Jack-Works/3ba26cb0326897ad9bdd64b70f7d5b98 to your computer and use it in GitHub Desktop.
Pause on exception, with catch, async version
function sleep(ms) {
return new Promise((resolve) => setTimeout(resolve, ms))
}
async function err() {
await sleep(200)
// debugger: pause on uncaught exception
// should pause on this
throw new Error("wow")
}
function err2() {
throw new Error("sync")
}
// How to implement this "exec" function??
// React version only works for the sync call stack (IIRC)
// https://github.com/facebook/react/blob/4c7036e807fa18a3e21a5182983c7c0f05c5936e/packages/shared/invokeGuardedCallbackImpl.js#L31
async function exec(f) {
return await f()
}
exec(err).catch((x) => console.warn(x.message)) // wow
exec(err2).catch((x) => console.warn(x.message)) // sync
@Jack-Works
Copy link
Author

Ok, I resolved it. The solution is too cursed and I'm happy to find a better solution

<body></body>
<script>
    function exec(f) {
        return new Promise((resolve, reject) => {
            async function wrappedF() {
                resolve(await f())
            }
            var i = document.createElement("iframe")
            window.addEventListener("unhandledrejection", (e) =>
                console.log(`From main realm ${e.reason?.message}`)
            )
            i.onload = () => {
                const document = i.contentDocument
                const window = i.contentWindow
                const button = document.createElement("button")
                document.body.appendChild(button)
                i.contentWindow.f = mainWorldTask
                button.onclick = () => {
                    new window.Promise((r) => {
                        wrappedF().then(r)
                    })
                }
                window.addEventListener("unhandledrejection", (e) =>
                    reject(e.reason)
                )
                setTimeout(() => {
                    button.click()
                }, 500)
            }
            document.body.appendChild(i)
        })
    }

    console.log(exec(mainWorldTask).catch((err) => console.log(err)))
    console.log(exec(ok))

    function sleep(ms) {
        return new Promise((resolve) => setTimeout(resolve, ms))
    }
    async function mainWorldTask() {
        console.log("hi")
        await sleep(200)
        throw new Error("err msg")
    }
    async function ok() {
        return 123
    }
</script>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment