Last active
February 18, 2020 17:30
-
-
Save mrister/b966c3f530e082b085fa8bfe53da7f5c to your computer and use it in GitHub Desktop.
A custom Node.js error example of ES5
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* | |
* @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