Skip to content

Instantly share code, notes, and snippets.

@Maximilianos
Last active August 29, 2015 14:22
Show Gist options
  • Save Maximilianos/6827f6a134ad8ddd387b to your computer and use it in GitHub Desktop.
Save Maximilianos/6827f6a134ad8ddd387b to your computer and use it in GitHub Desktop.
/**
* Error handling helper with builtin debugMode
* toggle
*
* @author: Max GJ Panas <http://maxpanas.com>
* @license: MIT
*
* Based on ideas from Nicholas Zakas expressed in his article:
* http://www.nczonline.net/blog/2009/04/28/javascript-error-handling-anti-pattern/
*/
/**
* Error handling helper with builtin
* debug mode toggle, for wrapping
* volatile functions
*
* @param fn
* @returns {*}
*/
function eR(fn) {
return function () {
if (eR.debug) {
return fn();
} else {
try {
return fn();
} catch (err) {
eR.handle(err, fn);
}
}
}
}
/**
* By default debug mode
* is turned off
*
* @type {boolean}
*/
eR.debug = false;
/**
* The default error handler
* simply logs to console
*
* Should be overwritten
*
* @param err
* @param fn
*/
eR.handle = function (err, fn) {
console.error(fn.name + ':', err);
};
export default eR;
@Maximilianos
Copy link
Author

And you could use it like so:

import eR from './eR';

// example function
function volatileFunc(msg) {
  throw new Error('Ooops!' + msg);
}

// as a callback
runsCallback(eR(volatileFunc));

// directly
eR(volatileFunc)("oooooh...");

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment