Skip to content

Instantly share code, notes, and snippets.

@DonutEspresso
Created May 17, 2019 01:45
Show Gist options
  • Save DonutEspresso/fdb48acacfaf058f291ddd0025f7d79d to your computer and use it in GitHub Desktop.
Save DonutEspresso/fdb48acacfaf058f291ddd0025f7d79d to your computer and use it in GitHub Desktop.
Callback Error Model
'use strict';
const mockClient = {};
// The Callback Error Model allows unintentional errors to bubble up and crash
// the process.
//
// With the Callback Error Model, it is impossible to catch these errors
// because try/catch doesn't work over subsequent ticks of the event loop.
//
// Errors that can be handled are propagated via callbacks.
function doStuff(cb) {
let rand = Math.random();
let x;
if (rand > 0.7) {
// throws a TypeError
// imagine this leaks a socket underneath the hood.
// $ echo $? => 1
mockClient.call();
} else if (rand > 0.3) {
// return error to be handled
// $ echo $? => 0
return cb(new Error('handle me!'))
}
// happy path
// $ echo $? => 0
return cb(null, 'success');
}
doStuff(function(err, msg) {
if (err) {
console.error('completed with non-fatal err: ', err);
} else {
console.log('completed!', msg);
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment