Created
March 7, 2017 14:37
-
-
Save lucalanca/51003cfc707ef2ce8789ad8abe9c638b to your computer and use it in GitHub Desktop.
Custom promise catch handling.
This file contains 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
// 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