Error Objects and Custom Errors

Updated · 9 min read
mediumES2026javascripterrorscustom-errorserror-causees2026

An error object is an instance of Error (or one of its subclasses) that describes a problem: what kind it is (name), what happened (message), where it happened (stack), and optionally what caused it (cause). JavaScript throws built-in error types for its own problems, and you can define custom error classes for your program's problems, so that code catching them can tell a validation error from a network error and react correctly.

In One Minute

  • Every error has name, message and (in all major engines) stack.
  • Built-in types: Error, TypeError, RangeError, SyntaxError, ReferenceError, URIError, EvalError, AggregateError.
  • new Error("message", { cause: originalError }) (ES2022) wraps a low-level error in a clearer one without losing it.
  • Error.isError(value) (ES2026) reliably checks whether a value is an error, even one created in another window or context.
  • Custom errors: class ValidationError extends Error { ... }, set this.name, add useful fields.

Error Properties

properties.js▶ Try it
const err = new RangeError("Amount must be positive");
 
console.log(err.name);
console.log(err.message);
console.log(err instanceof RangeError, err instanceof Error);
console.log(typeof err.stack);
console.log(err.stack.split("\n")[0]);
console.log(String(err));
Output
RangeError
Amount must be positive
true true
string
RangeError: Amount must be positive
RangeError: Amount must be positive
PropertyDescription
nameThe error type, such as "TypeError".
messageThe human-readable description passed to the constructor.
stackA string with the error and the call stack where it was created (not in the standard yet, but in every major engine).
causeThe underlying error or value that caused this one (ES2022).
errorsOn AggregateError only: the list of collected errors.

The stack is a snapshot of the call stack taken when the error object was created, which is why you should create errors where the problem is detected. Its exact format differs between engines; don't parse it in code.

Built-In Error Types

TypeThrown whenExample
TypeErrorA value is the wrong type for an operationCalling undefined(), reading a property of null
ReferenceErrorA name doesn't exist, or is used in its TDZconsole.log(undeclared)
SyntaxErrorCode or data can't be parsedJSON.parse("{bad}"), invalid code in eval
RangeErrorA number is outside its allowed rangenew Array(-1), (1).toFixed(200), too much recursion
URIErrorMalformed URI encodingdecodeURIComponent("%")
EvalErrorLegacy; not thrown by modern enginesn/a
AggregateErrorSeveral errors need reporting togetherPromise.any when all promises reject
builtin.js▶ Try it
const attempts = [
  () => null.balance,
  () => undeclaredTotal + 1,
  () => JSON.parse("{name: 'Navika'}"),
  () => (12.5).toFixed(101),
  () => decodeURIComponent("%E0%A4%A"),
];
 
for (const attempt of attempts) {
  try {
    attempt();
  } catch (err) {
    console.log(err.name.padEnd(15), err.message);
  }
}
Output
TypeError       Cannot read properties of null (reading 'balance')
ReferenceError  undeclaredTotal is not defined
SyntaxError     Expected property name or '}' in JSON at position 1 (line 1 column 2)
RangeError      toFixed() digits argument must be between 0 and 100
URIError        URI malformed

These messages come from V8 (Chrome and Node.js); Firefox and Safari word them differently. Code should check the type (err instanceof TypeError or err.name), never the message text.

Wrapping Errors with cause

Low-level errors often make poor messages for the layer above. JSON.parse says "Unexpected token"; the user needs "Couldn't load your saved settings". The cause option (ES2022) lets you throw a clearer error and keep the original attached:

cause.js▶ Try it
function loadSettings(text) {
  try {
    return JSON.parse(text);
  } catch (err) {
    throw new Error("Could not load saved settings", { cause: err });
  }
}
 
try {
  loadSettings("{oops}");
} catch (err) {
  console.log(err.message);
  console.log("Caused by:", err.cause.name);
  console.log(err.cause instanceof SyntaxError);
}
Output
Could not load saved settings
Caused by: SyntaxError
true

Logging tools and Node.js print the full chain ([cause]: SyntaxError: ...), so debugging still has every detail while the user sees a meaningful message.

Error.isError (ES2026)

err instanceof Error usually works, but it fails for errors created in another global environment (an iframe, a Web Worker message, a Node.js vm context), because each one has its own Error constructor. It can also be fooled by an ordinary object whose prototype was set to Error.prototype. Error.isError, new in ES2026, checks the object's internal structure instead:

is-error.js▶ Try it
const real = new TypeError("bad");
const fake = Object.create(Error.prototype);
 
console.log(Error.isError(real));
console.log(real instanceof Error);
console.log(Error.isError(fake), fake instanceof Error);
console.log(Error.isError({ name: "Error", message: "looks like one" }));
console.log(Error.isError("just a string"));
Output
true
true
false true
false
false

Explanation: fake passes instanceof Error (its prototype chain includes Error.prototype) but isn't really an error, and Error.isError correctly says false. It runs in Node.js 26 and current browsers (checked November 2026). Use it in code that receives values it didn't create, such as a generic error logger.

AggregateError

An AggregateError holds several errors at once, in its errors array. Promise.any throws one when every promise fails, and you can create one yourself to report many problems together:

aggregate.js▶ Try it
const problems = [new RangeError("line 2: bad amount"), new TypeError("line 5: missing name")];
const err = new AggregateError(problems, "Import found 2 problems");
 
console.log(err.name, "-", err.message);
for (const p of err.errors) console.log(" ", p.name, p.message);
Output
AggregateError - Import found 2 problems
  RangeError line 2: bad amount
  TypeError line 5: missing name

Custom Error Classes

When your program has its own kinds of failure, give each a class. Code that catches can then branch on the type, and the error can carry structured data, not just text:

custom.js▶ Try it
class ValidationError extends Error {
  constructor(field, message, options) {
    super(message, options);
    this.name = "ValidationError";
    this.field = field;
  }
}
 
class PaymentDeclinedError extends Error {
  constructor(reason, options) {
    super(`Payment declined: ${reason}`, options);
    this.name = "PaymentDeclinedError";
    this.reason = reason;
  }
}
 
function charge(payment) {
  if (!(payment.amount > 0)) throw new ValidationError("amount", "Amount must be positive");
  if (payment.card === "expired") throw new PaymentDeclinedError("card expired");
  return "Charged";
}
 
for (const p of [{ amount: 120, card: "ok" }, { amount: 0 }, { amount: 45, card: "expired" }]) {
  try {
    console.log(charge(p));
  } catch (err) {
    if (err instanceof ValidationError) console.log(`Fix the ${err.field} field: ${err.message}`);
    else if (err instanceof PaymentDeclinedError) console.log(`Ask for another card (${err.reason})`);
    else throw err;
  }
}
Output
Charged
Fix the amount field: Amount must be positive
Ask for another card (card expired)
StepWhy
extends ErrorInherits message, stack, cause and works with instanceof
super(message, options)Sets the message and passes { cause } through
this.name = "..."Otherwise name is just "Error" in logs
Extra fields (field, reason)Let catching code react without parsing messages

Errors and Security

Error messages can leak information. A login form that says "No account for navika@example.com" tells an attacker which emails are registered; a raw database error shown to a user can reveal table names. Show users a general message, and keep the details (including stack and cause) in server logs:

safe-message.js▶ Try it
function userMessage(err) {
  if (err.name === "ValidationError") return err.message;
  return "Something went wrong. Please try again.";
}
 
console.log(userMessage(Object.assign(new Error("Name is required"), { name: "ValidationError" })));
console.log(userMessage(new Error("connect ECONNREFUSED 10.0.0.5:5432 (payments_db)")));
Output
Name is required
Something went wrong. Please try again.

In Practice

The Fee Tracker's save function turns any low-level failure into one clear error type, keeps the original as cause, and lets the interface decide what to show:

save.js▶ Try it
class SaveError extends Error {
  constructor(what, options) {
    super(`Could not save ${what}`, options);
    this.name = "SaveError";
  }
}
 
function writeToStorage(record) {
  if (record.name.length > 20) throw new RangeError("Name too long for storage");
  return true;
}
 
function savePayment(record) {
  try {
    return writeToStorage(record);
  } catch (err) {
    throw new SaveError(`${record.name.slice(0, 10)}'s payment`, { cause: err });
  }
}
 
try {
  savePayment({ name: "Advitha Anamaneni-Long-Name", amount: 45 });
} catch (err) {
  console.log(err.name, "|", err.message, "|", err.cause.message);
  console.log(Error.isError(err), err instanceof SaveError);
}
Output
SaveError | Could not save Advitha An's payment | Name too long for storage
true true

Common Mistakes

Checking err.message text. It differs across engines. Check the type or a code.

Forgetting this.name in a custom error. Logs show plain Error. Set it in the constructor.

Losing the original error when rethrowing. throw new Error("Save failed") hides the reason. Pass { cause: err }.

Showing raw errors to users. They can leak internal details. Show a general message and log the rest.

Practice

Challenge: Create a NotFoundError class with an id property, throw it from findStudent(id) when the ID isn't in a list, and catch it to print No student with ID S-9.

Show solution
not-found.js▶ Try it
class NotFoundError extends Error {
  constructor(id) {
    super(`No student with ID ${id}`);
    this.name = "NotFoundError";
    this.id = id;
  }
}
 
const students = [{ id: "S-1", name: "Navika" }, { id: "S-2", name: "Srihitha" }];
 
function findStudent(id) {
  const student = students.find((s) => s.id === id);
  if (!student) throw new NotFoundError(id);
  return student;
}
 
try {
  console.log(findStudent("S-2").name);
  findStudent("S-9");
} catch (err) {
  if (err instanceof NotFoundError) console.log(err.message);
  else throw err;
}
Output
Srihitha
No student with ID S-9

Quick check: Error objects

3 questions
1Which error does reading a property of null throw?
2What is the cause option for?
3Why set this.name in a custom error class?

Key Takeaways

TaskCode
Throw a typed errorthrow new RangeError("...")
Wrap an errornew Error("...", { cause: err })
Check an error typeerr instanceof TypeError
Is it an error?Error.isError(value)
Custom errorclass X extends Error { constructor(m) { super(m); this.name = "X"; } }

Was this tutorial helpful?

Lesson 61 of 139