Skip to content

Instantly share code, notes, and snippets.

@woudsma
Last active November 27, 2020 22:37
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save woudsma/fe8598b1f41453208f0661f90ecdb98b to your computer and use it in GitHub Desktop.
Save woudsma/fe8598b1f41453208f0661f90ecdb98b to your computer and use it in GitHub Desktop.
Recursive try/catch statements for async/await functions in a nested object (using .catch)
// Simulates try/catch statements wrapping async functions in (nested) object
// Returns copy of original object with basic promise-rejection handling for async functions using .catch
// Saves the time of writing try/catch statements in every single async function
const trycatch = obj => Object.keys(obj)
.reduce((acc, curr) => ({ ...acc, [curr]: obj[curr] instanceof Function
? (...args) => obj[curr](...args).catch(::console.error)
: trycatch(obj[curr]) }), {})
// Example
const actions = (db) => trycatch({
async test(id) {
console.log(id)
},
get: {
async user(id) {
await db.users.get(id)
},
async session(id) {
throw new Error('TODO')
},
...
}
})
// Instead of:
const actions = (db) => ({
async test(id) {
try {
console.log(id)
} catch(err) {
console.error(err)
}
},
get: {
async user(id) {
try {
await db.users.get(id)
} catch(err) {
console.error(err)
}
},
async session(id) {
try {
throw new Error('TODO')
} catch(err) {
console.error(err)
}
},
...
}
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment