This repo is to compare various error handling patterns in JS and TS. Each pattern has its own branch.
- Then-Catch Pattern
- Try-Catch Pattern
- Mix'n'Match
.catch
Pattern - Async Wrapping Function - Single Level Pattern
- Non-Async Wrapping Function - Single Level Pattern
- Third Party Libraries
getJoke()
.then(joke => console.log(joke))
.catch(err => console.error(err))
try {
const joke = await getJoke()
console.log(joke)
} catch (err) {
console.error(err)
}
const joke = await getJoke().catch(err => {
console.error(err)
})
console.log(joke)
async function asyncWrap(promise) {
try {
const data = await promise
return [data, undefined]
} catch (err) {
return [undefined, err]
}
(async () => {
const [joke, err] = await asyncWrap(getJoke())
if ( joke ) { console.log(joke) }
if (err) { console.error(err) }
})()
function wrapIt(promise) {
return Promise.allSettled([promise]).then(([{value, reason}]) => {
return [value, reason]
})
}
const [joke, err] = wrapIt(getJoke())
if ( joke ) { console.log(joke) }
if (err) { console.error(err) }