Skip to content

Instantly share code, notes, and snippets.

@adambene
Last active January 22, 2017 13:38
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 adambene/1da05053b6508f2998d006481aa5d730 to your computer and use it in GitHub Desktop.
Save adambene/1da05053b6508f2998d006481aa5d730 to your computer and use it in GitHub Desktop.
Exception handling in ES6
// define an async operation that rejects if the path is not a string
const someAsyncOperation = async (path) => {
return new Promise((resolve, reject) => {
setTimeout(() => {
if (typeof path === 'string') {
resolve(`Hello Panda! Path is = ${path}`);
} else {
reject(new Error(`Path is not a string. Path (${typeof path}) = ${path}`));
}
}, 1000);
});
};
// handle exceptions the ES6 way with async-await
(async () => {
try {
const res = await someAsyncOperation(321);
console.log(res);
} catch (error) {
console.error('(FROM ASYNC/AWAIT) Error cause is:', error);
}
})();
// or the same the promise way
(() => {
someAsyncOperation(123)
.then((res) => {
console.log(res);
})
.catch((error) => {
console.error('(FROM PROMISE) Error cause is:', error);
});
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment