Error

The built-in error object with a message and a stack trace. The basis for exceptions and custom error classes.

Returns
A new Error object.
On this page

Example

#
JavaScript
const error = new Error('Lesson not found')

console.log(error.name)
console.log(error.message)
console.log(error instanceof Error)
console.log(error)
Console
Error
Lesson not found
true
Error: Lesson not found

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

#
Syntax
new Error()
new Error(message)
new Error(message, { cause })

error.name
error.message
error.cause
error.stack

Parameters

#
  • message

    string, optional

    The error description. Ends up in the error.message field.
  • options

    object, optional

    An object with a cause field, the reason for the error, usually another error.

More examples

#
A hierarchy of custom errors
JavaScript
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)
}
Console
NotEnoughFuelError: Needs 3 fuel, you have 1
true true
3

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.

The cause of an error in cause
JavaScript
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)
}
Console
Score not saved
{ status: 503 }
Built-in error kinds
JavaScript
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)
  }
}
Console
TypeError true
RangeError true
SyntaxError true
ReferenceError true

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 name in your custom error classes. Without it, the console and logs show a generic “Error,” and it’s harder to tell error kinds apart in catch.
  • The stack field 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

#

Spotted a mistake or missing an example? Write to us.