Skip to content

Instantly share code, notes, and snippets.

@debonx
Created January 19, 2020 19:20
Show Gist options
  • Save debonx/02058e46bf1804e5f32cd89f6b619df5 to your computer and use it in GitHub Desktop.
Save debonx/02058e46bf1804e5f32cd89f6b619df5 to your computer and use it in GitHub Desktop.
Node: Error handling, async Vs. error-first.
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`);
}
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)
}
}
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