Skip to content

Instantly share code, notes, and snippets.

@lucalanca
Created March 7, 2017 14:37
Show Gist options
  • Save lucalanca/51003cfc707ef2ce8789ad8abe9c638b to your computer and use it in GitHub Desktop.
Save lucalanca/51003cfc707ef2ce8789ad8abe9c638b to your computer and use it in GitHub Desktop.
Custom promise catch handling.
// transforms a rejection into a custom-format.
const catchTransformer = (fn, catchMap) => fn().catch(err => Promise.reject(catchMap(err)));
// Example of code that we don't control. The rejection follows its own format (e.g. fetch api).
const doSomethingAsyncThatFails = () =>
new Promise((resolve, reject) => {
setTimeout(() => reject(new Error('failed')), 1000);
});
// transform un-owned promise rejection into our rejection format
const doSomethingAsyncWithCustomRejection = () =>
catchTransformer(doSomethingAsyncThatFails, err => ({ id: '500', message: 'custom message' }));
doSomethingAsyncWithCustomRejection()
.then(res => console.log('result', result))
.catch(err => console.log('error', err));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment