create new type error javascript code example
Example 1: javascript throw new error
throw new Error("Error message here"); // Uncaught Error: Error message here
Example 2: js throw custom error
class CustomError extends Error {
constructor(foo = 'bar', ...params) {
// Pass remaining arguments (including vendor specific ones) to parent constructor
super(...params)
// Maintains proper stack trace for where our error was thrown (only available on V8)
if (Error.captureStackTrace) {
Error.captureStackTrace(this, CustomError)
}
this.name = 'CustomError'
// Custom debugging information
this.foo = foo
this.date = new Date()
}
}
try {
throw new CustomError('baz', 'bazMessage')
} catch(e) {
console.error(e.name) //CustomError
console.error(e.foo) //baz
console.error(e.message) //bazMessage
console.error(e.stack) //stacktrace
}