JS Custom Errors
In this page:
Creating Custom Errors
You create a custom error type by extending the built-in Error class, which gives your new error inherited behavior like a message property and a proper stack trace, while letting you add your own fields on top.
Example: Creating Custom Errors
class ValidationError extends Error {
constructor(message) {
super(message);
this.name = "ValidationError";
}
}
try {
throw new ValidationError("Invalid email");
} catch (e) {
console.log(e.name, e.message);
}
Adding Extra Information
A custom error class can accept extra constructor arguments and store them as additional properties, letting catch blocks access structured details beyond a plain message string.
Example: Adding Extra Information
class ValidationError extends Error {
constructor(message, field) {
super(message);
this.name = "ValidationError";
this.field = field;
}
}
try {
throw new ValidationError("Required field", "email");
} catch (e) {
console.log(e.field, e.message);
}
Catching Custom Errors
Because a custom error still extends Error, existing try/catch code keeps working; you can also check error instanceof YourErrorClass to handle that specific error type differently.
Example: Catching Custom Errors
class ValidationError extends Error {}
try {
throw new ValidationError("Bad input");
} catch (e) {
console.log(e instanceof ValidationError);
console.log(e instanceof Error);
}
Custom Error Use Cases
Custom errors are useful when different failure categories need different handling — for example, a ValidationError versus a NetworkError might trigger completely different UI responses.
Example: Custom Error Use Cases
class ValidationError extends Error {}
class NetworkError extends Error {}
function handle(err) {
if (err instanceof ValidationError) console.log("Show form message");
else if (err instanceof NetworkError) console.log("Retry request");
}
handle(new NetworkError("timeout"));
Custom Error Best Practices
Name custom error classes clearly (ending in Error by convention) and keep their extra properties minimal and well-documented so other developers know what to expect when catching them.
Example: Custom Error Best Practices
class OutOfStockError extends Error {
constructor(item) {
super(`${item} is out of stock`);
this.name = "OutOfStockError";
this.item = item;
}
}
try {
throw new OutOfStockError("Widget");
} catch (e) {
console.log(e.name, e.item);
}
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: