Last active
April 17, 2023 10:06
-
-
Save ourmaninamsterdam/2137a7cb24866fcf5fb9355f4ff89f02 to your computer and use it in GitHub Desktop.
Promise business/runtime logic error handling
This file contains hidden or 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
async function findUser(id: number) { | |
console.log('Getting user...'); | |
await sleep(1000); | |
// Mocked out API | |
if(id === 999) { | |
return [new Error('User not found'), undefined] | |
} | |
if(id === 1) { | |
return [undefined, { | |
name: 'Bilbo Baggins', | |
}] | |
} | |
return Promise.reject('Something bad happened'); | |
} | |
async function getUser() { | |
try{ | |
const [userNotFound, user] = await findUser(1); | |
// User is found | |
console.log('User found?', user); | |
} catch(err) { | |
throw err; | |
} | |
try{ | |
const [userNotFound, user] = await findUser(999); | |
// User is not found | |
console.log('User found?', userNotFound); | |
} catch(err) { | |
throw err; | |
} | |
try{ | |
const [userNotFound, user] = await findUser('No chance of working'); | |
// Runtime error | |
} catch(err) { | |
// throw new Error(err); | |
console.error(err); | |
} | |
} | |
getUser(); | |
async function sleep(ms: number) { | |
return new Promise((resolve)=> { | |
setTimeout(resolve, ms); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment