Skip to content

Instantly share code, notes, and snippets.

@jasoncrawford
Last active November 18, 2015 19:56
Show Gist options
  • Save jasoncrawford/9da0e14283b21e4d9c33 to your computer and use it in GitHub Desktop.
Save jasoncrawford/9da0e14283b21e4d9c33 to your computer and use it in GitHub Desktop.
JS custom errors
var util = require('util');
var extendable = require('./extendable');
// AppError is an error constructor that inherits from Error but is more easily extendable.
// You can inherit from it using 'extend' just like with Backbone constructors:
//
// var SpecialError = AppError.extend({
// name: 'SpecialError',
// initialize: function (foo, bar) {
// this.message = foo + " " + bar + "!";
// },
// })
//
// Then invoke like so: new SpecialError(foo, bar);
//
// It is advisable to define 'name', and to set this.message in initialize.
var AppError = function () {
this.initialize.apply(this, arguments);
AppError.super_.call(this, this.message);
if (!this.stack) this.stack = new Error(this.message).stack;
}
util.inherits(AppError, Error);
_.extend(AppError.prototype, {
name: 'AppError',
initialize: function (message) {
this.message = message;
},
})
extendable(AppError);
module.exports = AppError;
// This is a (simplified) Backbone-style extend function. You add it to constructors so that other
// constructors can easily inherit from them. E.g., if you have a general Model, and you want to be
// able to define User and Record as constructors that extend Model, you do:
//
// var extendable = prequire('server/utils/extend');
// extendable(Model);
// var User = Model.extend({...});
//
// ... just like with Backbone base constructors.
var util = require('util');
var extend = function (options) {
var parent = this;
var child = function () { return parent.apply(this, arguments); }; // jscs: nestedThisOk
if (options.constructorName) child.name = options.constructorName;
_.extend(child, parent); // Allows sub classes to be extendable
util.inherits(child, parent);
_.extend(child.prototype, options);
return child;
}
var extendable = function (constructor) {
constructor.extend = extend;
return constructor;
}
module.exports = extendable;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment