The base Error object.
To implement a custom error class, extend the Error class and set the name property to the name of the custom error class:
class MyError extends Error {
constructor(message) {
super(message)
this.name = 'MyError'
}
}
Errors are usually thrown with the throw keyword:
throw new MyError('failed to do something')
To check for a specific error, use the instanceof operator:
try {
throw new MyError('failed to do something')
} catch (e) {
if (e instanceof MyError) {
console.log('MyError caught')
} else {
throw e // re-throw all other errors
}
}
Error