Advanced Error Handling for Backbone using Radio.
Try, throw, and catch namespaced errors using Backbone.Radio with built-in promise handling.
Backbone Errors introduces the concept of namespacing errors. Throwing an error with a name will attempt to be caught by a handler with the same name, otherwise it will use the "default" handler.
Errors.catch('default', (name) => {
console.log(`Nobody caught the ${name}.`);
});
Errors.throw('baseball');
// >> Nobody caught the baseball.
Errors.catch('baseball', err => {
console.log(`I caught the baseball.`);
});
Errors.try('baseball', () => {
throw new Error();
});
// >> I caught the baseball.
In order to setup a handler to catch an error use the Errors.catch
method.
Errors.catch('football', err => {
console.log('Caught it!');
});
There are two primary ways of throwing an error. The first is to call the
Errors.throw
method.
Errors.throw('football');
// >> Caught it!
The second is to use the Errors.try
method which will execute a callback, and
if that callback throws it will forward the error to the proper handler.
Errors.catch('hockey', err => {
console.log(`Off go the ${err.message}`)
});
let isFighting = false;
function callback() {
if (isFighting) {
throw new Error('gloves');
} else {
return 'Start a fight!';
}
}
Errors.try('hockey', callback);
// 'Start a fight!'
isFighting = true;
Errors.try('hockey', callback);
// >> Off go the gloves!
If you would like to stop catching errors. You use the stopCatching
method.
Errors.catch('basketball', () => {
console.log('Caught it.');
})
Errors.throw('basketball');
// >> Caught it.
Errors.stopCatching('basketball');
Errors.throw('basketball');
// >> Nobody caught the basketball.
git clone [email protected]:thejameskyle/backbone-errors.git && cd backbone-errors
Make sure Node.js and npm are installed.
npm install
npm test
===
© 2014 James Kyle. Distributed under ISC license.