Skip to content

Instantly share code, notes, and snippets.

@veggiemonk
Created March 4, 2018 08:49
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save veggiemonk/b43633cdf40927d0babbc2f79edeffc2 to your computer and use it in GitHub Desktop.
Save veggiemonk/b43633cdf40927d0babbc2f79edeffc2 to your computer and use it in GitHub Desktop.
Javascript: Custom error with stack
/*
http://jsbin.com/rolojuhuya/1/
https://stackoverflow.com/questions/8802845/inheriting-from-the-error-object-where-is-the-message-property
https://stackoverflow.com/questions/783818/how-do-i-create-a-custom-error-in-javascript
*/
function CustomError(message, somethingElse) {
var error = Error.call(this, message);
this.name = 'CustomError';
this.message = error.message;
this.stack = error.stack;
this.customProperty = somethingElse;
}
CustomError.prototype = Object.create(Error.prototype);
CustomError.prototype.constructor = CustomError;
var customError = new CustomError('some error message', 42);
console.log(customError.name + ' => CustomError');
console.log(customError.message + ' => some error message');
console.log(customError.customProperty + ' => 42');
console.log((customError instanceof Error) + ' => true');
console.log((customError instanceof CustomError) + ' => true');
console.log('constructor: ' + customError.constructor);
console.log('toString: ' + customError.toString());
console.log('stack: ' + customError.stack);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment