Skip to content

Instantly share code, notes, and snippets.

@ryanmorr
Created April 1, 2024 20:24
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 ryanmorr/108d45f6c0f5d6214bcccfee8201b022 to your computer and use it in GitHub Desktop.
Save ryanmorr/108d45f6c0f5d6214bcccfee8201b022 to your computer and use it in GitHub Desktop.
Wrap a try/catch block with a promise for easy error handling
function attempt(fn) {
return new Promise((resolve, reject) => {
try {
resolve(fn());
} catch(e) {
reject(e);
}
});
}
// Usage:
attempt(() => (0)()).then((val) => {
console.log('pass');
}).catch((e) => {
console.log('fail');
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment