-
-
Save lafiosca/cdbc49b94dab11c88279d3a5ccafbd2c to your computer and use it in GitHub Desktop.
try/catch behavior with returned async functions that throw
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'use strict'; | |
const x1 = () => { | |
console.log('x1'); | |
throw new Error('hi'); | |
}; | |
const x2 = async () => { | |
console.log('x2'); | |
throw new Error('hi again'); | |
}; | |
const y1a = () => { | |
console.log('y1a'); | |
try { | |
x1(); | |
} catch (error) { | |
console.log('y1a catch:', error.message); | |
} | |
}; | |
const y1b = () => { | |
console.log('y1b'); | |
try { | |
return x1(); | |
} catch (error) { | |
console.log('y1b catch:', error.message); | |
} | |
}; | |
const y2a = async () => { | |
console.log('y2a'); | |
try { | |
await x2(); | |
} catch (error) { | |
console.log('y2a catch:', error.message); | |
} | |
}; | |
const y2b = async () => { | |
console.log('y2b'); | |
try { | |
return x2(); | |
} catch (error) { | |
console.log('y2b catch:', error.message); | |
} | |
}; | |
(async () => { | |
try { | |
await y1a(); | |
console.log(); | |
await y1b(); | |
console.log(); | |
await y2a(); | |
console.log(); | |
await y2b(); | |
} catch (error) { | |
console.log('outer catch:', error.message); | |
} | |
console.log(); | |
console.log('again without outer try/catch...'); | |
await y2b(); | |
})(); | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
y1a | |
x1 | |
y1a catch: hi | |
y1b | |
x1 | |
y1b catch: hi | |
y2a | |
x2 | |
y2a catch: hi again | |
y2b | |
x2 | |
outer catch: hi again | |
again without outer try/catch... | |
y2b | |
x2 | |
(node:37501) UnhandledPromiseRejectionWarning: Error: hi again | |
[...] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment