Skip to content

Instantly share code, notes, and snippets.

@tlbdk
Created January 25, 2023 21:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tlbdk/726e41bcf2ccfe7fa96ce20baf77d69d to your computer and use it in GitHub Desktop.
Save tlbdk/726e41bcf2ccfe7fa96ce20baf77d69d to your computer and use it in GitHub Desktop.
Test out how stack traces are formed
/* eslint-disable no-console */
const promise = new Promise<void>((resolve, reject) => {
reject(new Error())
})
async function throwsFromPromiseOutside(): Promise<void> {
return await promise
}
async function throwsFromPromiseOutsideFixed(): Promise<void> {
try {
await promise
} catch (e) {
Error.captureStackTrace(e)
//Object.defineProperty(e, 'stack', { enumerable: true })
console.log(JSON.stringify(e, null, 2))
throw e
}
}
async function throwsFromPromise(): Promise<void> {
return await new Promise<void>((resolve, reject) => {
reject(new Error())
})
}
async function throwsFromAsync(): Promise<void> {
throw new Error()
}
function throwsSync(): void {
throw new Error()
}
async function main(): Promise<void> {
try {
await throwsFromPromiseOutside()
} catch (e) {
console.log(`throwsFromPromiseOutside`)
console.error(e)
}
try {
await throwsFromPromiseOutsideFixed()
} catch (e) {
console.log(`throwsFromPromiseOutsideFixed`)
console.error(e)
}
try {
await throwsFromPromise()
} catch (e) {
console.log(`throwsFromPromise`)
console.error(e)
}
try {
console.log(`throwsFromAsync`)
await throwsFromAsync()
} catch (e) {
console.error(e)
}
try {
console.log(`throwsSync`)
await throwsSync()
} catch (e) {
console.error(e)
}
}
main().catch(e => {
console.error(e)
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment