Skip to content

Instantly share code, notes, and snippets.

@mrister
Last active February 18, 2020 17:30
Show Gist options
  • Save mrister/b966c3f530e082b085fa8bfe53da7f5c to your computer and use it in GitHub Desktop.
Save mrister/b966c3f530e082b085fa8bfe53da7f5c to your computer and use it in GitHub Desktop.
A custom Node.js error example of ES5
/**
*
* @param {String } name is the name of the newly created error
* @param {Function} [init] optional initialization function
* @returns {Err} The new Error
*/
function createError(name, init) {
function Err(message) {
Error.captureStackTrace(this, this.constructor);
this.message = message;
init && init.apply(this, arguments);
}
Err.prototype = new Error();
//set the name property
Err.prototype.name = name;
// set the constructor
Err.prototype.constructor = Err;
return Err;
}
// define new error
var MyError = createError('MyError', function (name, invalid) { this.message = 'The name ' + name + ' is invalid because of ' + invalid; });
// throw it
throw new MyError('test', 'problems');
//MyError: The name test is invalid because of problems
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment