JavaScript Error

Beginner
9 min read
Updated: Nov 2026
3 examples
Error handling

Definition and Usage

An Error object describes a problem that happened while your program was running. You create one with new Error("message") and report it with throw. JavaScript also creates error objects by itself, for example when your code reads a property of null.

When an error is thrown, the normal flow stops and JavaScript looks for the nearest try...catch block. If it finds one, your catch code handles the problem and the program can go on. If it finds none, the program stops and the error is printed in the console.

This page explains the idea. The Error Methods index links the full guides for Error.captureStackTrace(), Error.isError() and toString().

Every error has a name and a message.

err.name tells you the kind of problem, such as TypeError. err.message explains it in words. err.stack adds the list of functions that were running.

JavaScript Syntax

Create an error, read its parts, then throw and catch it:

JavaScript
const err = new Error("Something went wrong");   // create an error object

console.log(err.name);      // "Error"
console.log(err.message);   // "Something went wrong"

try {
  throw err;                // report the problem
} catch (e) {
  console.log(e.message);   // handle it here
} finally {
  console.log("done");      // always runs
}

const wrapped = new Error("Save failed", { cause: err });  // keep the original error

Core Ideas

Ideas every Error tutorial in this series builds on:

IdeaExampleRemember
new Error()new Error("Disk full")Creates an error; the message is optional
nameerr.nameThe kind of error, such as "TypeError"
messageerr.messageA readable explanation of the problem
stackerr.stackText listing the functions that were running
causenew Error("Failed", { cause: err })Keeps the original error inside a new one
throwthrow new Error("Oops")Stops the current code and jumps to the nearest catch
try...catchtry { ... } catch (err) { ... }Handles a thrown error so the program can continue
finallyfinally { cleanup(); }Runs whether or not an error happened
instanceoferr instanceof TypeErrorTells you which kind of error you caught

Built-in Error Types

JavaScript creates these error types by itself. You can create them too with new:

TypeJavaScript throws it when...Example
ErrorYou or a library create a general errornew Error("Oops")
TypeErrorA value is not the type an operation needsnull.length
ReferenceErrorYou use a variable that does not existmissingVariable
RangeErrorA number is outside the allowed rangenew Array(-1)
SyntaxErrorCode or text cannot be parsedJSON.parse("{bad")
URIErrorA URI function receives bad inputdecodeURIComponent("%")
AggregateErrorSeveral errors are wrapped into one, for example by Promise.any()new AggregateError([e1, e2])

All of these types extend Error, so err instanceof Error is true for each of them. When you handle errors, check the specific type first (err instanceof TypeError) and fall back to the general Error. An older type called EvalError still exists, but modern JavaScript does not throw it.

How Errors Work

Throw stops the current code

The moment throw runs, the rest of that function is skipped. JavaScript walks back through the functions that called it until it finds a catch.

Errors travel up the call stack

You do not have to catch an error where it happens. A function can let it move up to a caller that knows what to do. Example 3 shows the path.

finally always runs

Use finally for cleanup, such as closing a file or hiding a loading spinner. It runs after a normal finish, after a caught error, and even when the error is not caught here.

You can throw any value

JavaScript accepts throw "oops" and throw 404, but then you lose the message and the stack. Always throw Error objects, and use Error.isError() in a catch block when you are not sure what you received.

Add context with cause

When you catch a low-level error and throw a friendlier one, pass the original as { cause: err }. The reader of the log can then see both. Example 2 shows it.

Real-Life Uses

Errors are how code says "I cannot continue, and here is why". Typical places you will meet them:

UseWhat the error does
Form validationThrow a ValidationError with a clear message when a field is empty or invalid.
Failed network callsCreate an Error when fetch() answers with a bad status, so the caller can show a retry button.
Reading JSONJSON.parse() throws a SyntaxError for broken text. Catch it and fall back to default settings.
Logging and debuggingShow err.message to the user and keep err.stack in the log so developers can find the line that failed.
Custom error classesClasses such as PaymentError let your code handle different problems in different ways.

JavaScript Examples

Three short programs that show errors at work. Each one only prints plain text, so the output is the same in Node.js and in the browser console.

Example 1 — Meet the Built-in Error Types

Each test breaks a rule on purpose. The catch block prints the type of error JavaScript created.

JavaScript
const tests = [
  ["null.length", () => null.length],
  ["missingVariable", () => missingVariable],
  ["new Array(-1)", () => new Array(-1)],
  ["JSON.parse('{bad')", () => JSON.parse("{bad")],
  ["decodeURIComponent('%')", () => decodeURIComponent("%")]
];

for (const [label, test] of tests) {
  try {
    test();
  } catch (err) {
    console.log(label + " -> " + err.name + ", instanceof Error: " + (err instanceof Error));
  }
}

How It Works

  1. Wrap each test. Every test is a small function. Calling it inside try lets the loop continue after an error instead of stopping the program.
  2. JavaScript picks the type. Reading a property of null is a TypeError, an unknown variable is a ReferenceError, and so on. err.name shows which one it was.
  3. One family. The last part of each line shows that every type is also an Error, so instanceof Error is always true.

Example 2 — Create a Custom Error with a Cause

A payment function turns a low-level RangeError into a friendlier PaymentError and keeps the original inside cause.

JavaScript
class PaymentError extends Error {
  constructor(message, options) {
    super(message, options);
    this.name = "PaymentError";
  }
}

function chargeCard(amount) {
  try {
    if (amount > 500) {
      throw new RangeError("Limit is 500");
    }
    return "Charged " + amount;
  } catch (err) {
    throw new PaymentError("Payment failed", { cause: err });
  }
}

try {
  console.log(chargeCard(120));
  console.log(chargeCard(900));
} catch (err) {
  console.log(err.name + ": " + err.message);
  console.log("Cause: " + err.cause);
  console.log("Is a PaymentError: " + (err instanceof PaymentError));
}

How It Works

  1. Extend Error. PaymentError is an Error with its own name. It passes the optional second argument on to super(), which is how cause gets stored.
  2. Translate the problem. For 900 the inner code throws a RangeError. The catch block wraps it in a PaymentError and keeps the original as cause.
  3. Read both. The outer catch prints the friendly error, then err.cause, which JavaScript turns into text with toString().

Example 3 — Watch an Error Travel Up and Run finally

The error starts in readConfig(), passes through startApp() and is caught in the main code.

JavaScript
function readConfig() {
  throw new Error("config.json is missing");
}

function startApp() {
  console.log("Starting app");
  try {
    readConfig();
    console.log("This line is skipped");
  } finally {
    console.log("Cleanup always runs");
  }
}

try {
  startApp();
} catch (err) {
  console.log("Caught in main: " + err.message);
}

console.log("Program keeps running");
Methods index

How It Works

  1. Throw and skip. readConfig() throws at once, so the line after the call in startApp() never runs.
  2. finally runs on the way out. startApp() has no catch, but its finally block still prints before the error moves on to the caller.
  3. Caught at the top. The outer catch receives the same error and prints its message. Because it was handled, the last line still runs.

Error Methods

Error has two static methods and one instance method. Each one has its own tutorial:

MethodWhat it does
Error.captureStackTrace()Add a stack property to any object and hide helper functions from it (V8 feature).
Error.isError()Check whether a value is a real Error object, more reliably than instanceof.
toString()Turn an error into one line of text: name: message.

Full list: Error Methods index.

Frequently Asked Questions

An Error is an object that describes a problem in your program. It has a name (the kind of error), a message (the explanation) and usually a stack (the functions that were running). You create one with new Error("message") and report it with throw.
Write throw new Error("message") where the problem happens. Put the risky code inside try { ... } and handle the problem in catch (err) { ... }. Use finally { ... } for cleanup code that must always run.
Error is the general type. TypeError, RangeError, ReferenceError, SyntaxError and URIError are more specific types that JavaScript throws for particular problems, such as the wrong kind of value or a number out of range. All of them extend Error.
JavaScript allows it, but it is a bad habit: a string has no stack and no name, so debugging is harder. Always throw Error objects. When you catch values from code you do not control, check them with Error.isError() before you read message.
The finally block runs after try and catch no matter what happened: when the code finished normally, when an error was caught, and even when the error was not caught in this function. It is the right place for cleanup.

Browse the Error methods

Open the index for Error.captureStackTrace(), Error.isError() and toString(): syntax, runnable examples, and FAQs.

Error Methods index →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

15 people found this page helpful