Created
January 19, 2020 19:20
-
-
Save debonx/02058e46bf1804e5f32cd89f6b619df5 to your computer and use it in GitHub Desktop.
Node: Error handling, async Vs. error-first.
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
const api = require('./node-error-api.js'); | |
// Not an error-first callback | |
let callbackFunc = (data) => { | |
console.log(`Something went right. Data: ${data}\n`); | |
}; | |
try { | |
api.naiveErrorProneAsyncFunction('problematic input', callbackFunc); | |
} catch(err) { | |
console.log(`Something went wrong. ${err}\n`); | |
} |
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
module.exports = { | |
errorProneAsyncApi: (input, callback) => { | |
console.log(`Running errorProneAsyncApi with input: ${input}...\n`) | |
setTimeout(() => { | |
let myErr; | |
if (input === 'problematic input') { | |
myErr = new Error('whoops') | |
callback(myErr) | |
} else { | |
let responseData = `Received valid input "${input}"` | |
callback(myErr, responseData) | |
} | |
}, 0) | |
}, | |
naiveErrorProneAsyncFunction: (input, callback) => { | |
console.log(`Running naiveErrorProneAsyncFunction with input: ${input}...\n`) | |
setTimeout(() => { | |
if (input === 'problematic input') { | |
throw new Error('whoops') | |
} else { | |
let responseData = `Received valid input "${input}"` | |
callback(responseData) | |
} | |
}, 0) | |
} | |
} | |
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
const api = require('./node-error-api.js'); | |
// An error-first callback | |
let errorFirstCallback = (err, data) => { | |
if (err) { | |
console.log(`Something went wrong. ${err}\n`); | |
} else { | |
console.log(`Something went right. Data: ${data}\n`); | |
} | |
}; | |
api.errorProneAsyncApi('problematic input', errorFirstCallback); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment