Encodera

Thanks for reading!

Donate to the site — we work hard for you.

JavaScript reference

Error

The base error class: created and thrown with throw.

Available since: ES1

Syntax

new Error(message, options)

Parameters

ParameterTypeDescription
messagestringOptional. A readable description of the error.
optionsobjectOptional. An object with a cause field — the original reason for the error.

Return value

ErrorAn error object with name, message, stack and cause properties.

Examples

Throwing and catching an error:

try {
  throw new Error('Something went wrong');
} catch (error) {
  console.log(error.name);
  console.log(error.message);
}

Output:

Error
Something went wrong

A custom error class:

class ValidationError extends Error {
  constructor(field, message) {
    super(message);
    this.name = 'ValidationError';
    this.field = field;
  }
}
 
try {
  throw new ValidationError('email', 'Email is required');
} catch (error) {
  console.log(error instanceof ValidationError, error.field);
  console.log(String(error));
}

Output:

true email
ValidationError: Email is required

Notes

Throw Error objects, not strings: they have a stack — the list of calls showing where the error happened.

See also

  • try...catch — Catches errors so the program does not stop.
  • throw — Throws an error and stops the function.
  • TypeError — A wrong type error — for example, calling a method on undefined.
  • Error.prototype.cause — The original reason for an error — so it is not lost when rethrowing.

In the tutorial

  • Errors and try...catch — Error handling in JavaScript: try, catch and finally blocks, the error object, the throw statement and built-in error types.

Thanks for reading!

Donate to the site — we work hard for you.