js custom error code example
Example 1: javascript throw new error
throw new Error("Error message here");
Example 2: js throw custom error
class CustomError extends Error {
constructor(foo = 'bar', ...params) {
super(...params)
if (Error.captureStackTrace) {
Error.captureStackTrace(this, CustomError)
}
this.name = 'CustomError'
this.foo = foo
this.date = new Date()
}
}
try {
throw new CustomError('baz', 'bazMessage')
} catch(e) {
console.error(e.name)
console.error(e.foo)
console.error(e.message)
console.error(e.stack)
}
Example 3: javascript string error
Error.prototype.toString = function() {
'use strict';
var obj = Object(this);
if (obj !== this) {
throw new TypeError();
}
var name = this.name;
name = (name === undefined) ? 'Error' : String(name);
var msg = this.message;
msg = (msg === undefined) ? '' : String(msg);
if (name === '') {
return msg;
}
if (msg === '') {
return name;
}
return name + ': ' + msg;
};