Created
March 4, 2018 08:49
-
-
Save veggiemonk/b43633cdf40927d0babbc2f79edeffc2 to your computer and use it in GitHub Desktop.
Javascript: Custom error with stack
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
/* | |
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