Error
The built-in error object with a message and a stack trace. The basis for exceptions and custom error classes.
- Returns
- A new
Errorobject.
Example
#const error = new Error('Lesson not found')
console.log(error.name)
console.log(error.message)
console.log(error instanceof Error)
console.log(error)Definition and usage
#Error is the built-in class describing an error. You create one with new Error("message") and usually throw it right away with throw. Every error has a name field with the kind of error, message with the description, and stack, the trace of calls leading to where it was created. The stack trace helps you find the source of the problem.
JavaScript has several built-in error variants: TypeError (wrong type, e.g. calling something that isn’t a function), RangeError (a value outside the allowed range), SyntaxError (invalid syntax, e.g. in text passed to JSON.parse()), ReferenceError (a reference to a variable that doesn’t exist), and URIError. They all extend Error, so instanceof Error returns true for them. AggregateError collects several errors at once, for example from Promise.any().
You create custom error classes with extends Error. It’s worth setting name in them and adding fields with extra information, like a form field name. The cause option in the second argument, new Error("message", { cause }), attaches a reason: the original error, or data that helps explain what went wrong.
Syntax
#new Error()
new Error(message)
new Error(message, { cause })
error.name
error.message
error.cause
error.stackParameters
#message
string, optional
The error description. Ends up in theerror.messagefield.options
object, optional
An object with acausefield, the reason for the error, usually another error.
More examples
#class AppError extends Error {
constructor(message, options) {
super(message, options)
this.name = this.constructor.name
}
}
class NotEnoughFuelError extends AppError {
constructor(needed, available) {
super(`Needs ${needed} fuel, you have ${available}`)
this.needed = needed
}
}
try {
throw new NotEnoughFuelError(3, 1)
} catch (error) {
console.log(error)
console.log(error instanceof AppError, error instanceof Error)
console.log(error.needed)
}The base class sets name to the name of the actual class, so every further error kind gets the right name without repeating code. If your build tool shortens class names, set name by hand.
function saveScore(response) {
if (!response.ok) {
throw new Error('Score not saved', { cause: { status: response.status } })
}
return 'Saved'
}
try {
saveScore({ ok: false, status: 503 })
} catch (error) {
console.log(error.message)
console.log(error.cause)
}const attempts = [
() => null.length,
() => new Array(-1),
() => JSON.parse('{broken'),
() => missingVariable
]
for (const attempt of attempts) {
try {
attempt()
} catch (error) {
console.log(error.name, error instanceof Error)
}
}Browser support
#Widely available
Works in all modern browsers, phones included. You can use it without worry.
- Chrome
- Edge
- Firefox
- Safari
Good practices
#- Write messages that say what happened and what to do next. “Out of fuel. Come back tomorrow” helps more than “Error 17.”
- Set
namein your custom error classes. Without it, the console and logs show a generic “Error,” and it’s harder to tell error kinds apart incatch. - The
stackfield is handy for debugging, but its format differs between browsers. Don’t parse it in your program’s logic, and don’t show it to users.
Related entries
#- throwThrows an exception: stops the current code and passes the error to the nearest catch block.
- try...catchCatches errors thrown in the try block and handles them in catch. The optional finally always runs.
- extendsCreates a derived class that inherits another class’s methods and can extend or override them.
- instanceofChecks whether an object was created by a given class, or by a class that inherits from it.
- Promise.prototype.catch()Registers an error-handling function that runs when the promise is rejected.
Spotted a mistake or missing an example? Write to us.