Custom Error example
by Artem
JavaScript
var SpecialError = function(message) {
this.message = message;
this.stack = (new Error()).stack;
};
SpecialError.prototype = Object.create(Error.prototype);
SpecialError.prototype.constructor = SpecialError;
// -------------------------------------------------
var OtherError = (function() {
return {
constructor: function(message) {
this.message = message;
this.stack = (new Error()).stack;
return this;
}
};
})();
console.log(OtherError);
OtherError = Object.create(Error.prototype);
var other = Object.create(OtherError).constructor('My Error');
console.log(other);
// -------------------------------------------------
try {
throw other;
//throw new SpecialError('special');
} catch (e) {
if (e instanceof Error) {
//console.log('OK: ', e);
} else {
//console.log('NOT OK: ', e);
throw e;
}
}