Skip to content

Instantly share code, notes, and snippets.

@jdubie
Created August 6, 2013 18:35
Show Gist options
  • Save jdubie/6167263 to your computer and use it in GitHub Desktop.
Save jdubie/6167263 to your computer and use it in GitHub Desktop.
A possible nodejs error handling convention
/* In api.js */
/**
* @param callback {function(err)}
*
* err.type in { 'malformed', 'forbidden', 'service_unavailable' }
*/
exports.connect = function (callback) {
var err = new Error('Service Unavailable, try again');
err.type = 'service_unavailable';
callback(err);
};
/* In client.js */
var api = require('./api');
api.connect(function (err) {
if (err instanceof Error) {
switch(err.type) {
case 'malformed':
// handle malformed requests
break;
case 'forbidden':
// handle forbidden requests
break;
case 'service_unavailable':
// handle service unavailable
break;
default:
// handle this case
}
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment