Error Objects and Custom Errors
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,messageand (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 { ... }, setthis.name, add useful fields.
Error Properties
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));RangeError
Amount must be positive
true true
string
RangeError: Amount must be positive
RangeError: Amount must be positive| Property | Description |
|---|---|
name | The error type, such as "TypeError". |
message | The human-readable description passed to the constructor. |
stack | A string with the error and the call stack where it was created (not in the standard yet, but in every major engine). |
cause | The underlying error or value that caused this one (ES2022). |
errors | On 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
| Type | Thrown when | Example |
|---|---|---|
TypeError | A value is the wrong type for an operation | Calling undefined(), reading a property of null |
ReferenceError | A name doesn't exist, or is used in its TDZ | console.log(undeclared) |
SyntaxError | Code or data can't be parsed | JSON.parse("{bad}"), invalid code in eval |
RangeError | A number is outside its allowed range | new Array(-1), (1).toFixed(200), too much recursion |
URIError | Malformed URI encoding | decodeURIComponent("%") |
EvalError | Legacy; not thrown by modern engines | n/a |
AggregateError | Several errors need reporting together | Promise.any when all promises reject |
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);
}
}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 malformedThese 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:
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);
}Could not load saved settings
Caused by: SyntaxError
trueLogging 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:
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"));true
true
false true
false
falseExplanation: 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:
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);AggregateError - Import found 2 problems
RangeError line 2: bad amount
TypeError line 5: missing nameCustom 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:
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;
}
}Charged
Fix the amount field: Amount must be positive
Ask for another card (card expired)| Step | Why |
|---|---|
extends Error | Inherits 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:
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)")));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:
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);
}SaveError | Could not save Advitha An's payment | Name too long for storage
true trueCommon 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
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;
}Srihitha
No student with ID S-9Key Takeaways
| Task | Code |
|---|---|
| Throw a typed error | throw new RangeError("...") |
| Wrap an error | new Error("...", { cause: err }) |
| Check an error type | err instanceof TypeError |
| Is it an error? | Error.isError(value) |
| Custom error | class X extends Error { constructor(m) { super(m); this.name = "X"; } } |
Was this tutorial helpful?