JavaScript Notes
Learn to create custom error classes in JavaScript by extending Error. Build ValidationError, NotFoundError, NetworkError with extra properties and instanceof checks.
When JavaScript's built-in error types (TypeError, RangeError, Error) are not specific enough for your application's needs, you can create custom error classes by extending Error. Custom errors let you:
- Add extra properties (error codes, HTTP status, field names)
- Use
instanceofto handle different error types differently - Build error hierarchies that match your domain
- Give callers precise information about what went wrong
📊 Custom Error Hierarchy Diagram
💻 Example 1 — Simple Custom Error Class
class ValidationError extends Error {
constructor(message, field) {
super(message); // call Error constructor with message
this.name = "ValidationError"; // override the name
this.field = field; // extra property
// Fix stack trace in V8 (Node.js / Chrome)
if (Error.captureStackTrace) {
Error.captureStackTrace(this, ValidationError);
}
}
}
function validateEmail(email) {
if (!email) throw new ValidationError("Email is required", "email");
if (!email.includes("@")) throw new ValidationError("Invalid email format", "email");
return email.toLowerCase().trim();
}
try {
validateEmail("not-an-email");
} catch (error) {
console.log(error instanceof ValidationError); // true
console.log(error instanceof Error); // true — still an Error!
console.log(error.name);
console.log(error.message);
console.log(error.field);
}true true ValidationError Invalid email format email
💻 Example 2 — Error Hierarchy for a Web Application
✅ {"id":1,"name":"Riya"}
400 Validation: [id] ID must be a number
400 Validation: [id] ID must be positive
401 Auth: Authentication required
404 Not Found: User with id=200 not found💻 Example 3 — Custom Error with Multiple Fields (Form Validation)
Form validation failed: 4 error(s) ❌ username: Username must be at least 3 characters ❌ email: Valid email is required ❌ password: Password must be at least 8 characters ❌ confirmPassword: Passwords do not match
📋 Custom Error Checklist
| Step | Code |
|---|---|
Extend Error | class MyError extends Error { ... } |
Call super(message) | Required — sets this.message |
Set this.name | Use this.name = this.constructor.name |
| Add custom properties | this.field, this.code, this.statusCode, etc. |
| Fix stack trace (optional) | Error.captureStackTrace(this, MyError) |
Check with instanceof | if (e instanceof MyError) { ... } |
⚠️ Common Mistakes
❌ Mistake 1 — Forgetting super(message)
class BadError extends Error {
constructor(msg) {
// Missing super(msg)!
this.name = "BadError";
}
}
const e = new BadError("oops");
console.log(e.message); // "" — empty! super was not called❌ Mistake 2 — Not Setting this.name
class DatabaseError extends Error {
constructor(msg) { super(msg); }
// Missing: this.name = "DatabaseError"
}
const e = new DatabaseError("Connection failed");
console.log(e.name); // "Error" — not "DatabaseError"Error
❌ Mistake 3 — Using instanceof Without Extending Error
class Fail {
constructor(msg) { this.message = msg; }
}
try { throw new Fail("oops"); }
catch(e) {
console.log(e instanceof Error); // false — not a real Error subclass
console.log(e.stack); // undefined — no stack trace
}false undefined
🎯 Key Takeaways
- Custom errors are created by
class MyError extends Error - Always call
super(message)first — it setsthis.message - Set
this.name = this.constructor.namefor correct.nameproperty - Add extra properties (
.field,.code,.statusCode) for structured information - Use
instanceofto distinguish error types incatchblocks - Build error hierarchies (
AppError → ValidationError, NotFoundError) for clean handling - Custom errors make APIs much more developer-friendly
❓ Interview Questions
Q1. Why create custom error classes instead of using plain Error? > Custom errors let you add extra properties (field names, error codes, HTTP status), enable precise instanceof checking so different errors trigger different handling logic, and make your API self-documenting — callers know exactly what can go wrong.
Q2. How do you create a custom error in JavaScript? > class ValidationError extends Error { constructor(msg, field) { super(msg); this.name = "ValidationError"; this.field = field; } }. The key steps: extend Error, call super(message), set this.name, add custom properties.
Q3. Why must you call super(message) in the custom error constructor? > super(message) calls the Error constructor, which sets this.message and this.stack. Without it, the error won't have a message or stack trace.
Q4. How do you check which custom error type was thrown? > Use instanceof: if (error instanceof ValidationError) { ... }. Because custom errors extend Error, they also pass error instanceof Error.
Q5. What is Error.captureStackTrace and should you always use it? > It's a V8-specific method (Node.js/Chrome) that removes the error constructor from the stack trace, making the trace start at the point where the error was thrown. It improves debugging. It's optional — check if (Error.captureStackTrace) before calling it.
Q6. What is an operational error vs a programmer error? > Operational errors are expected failures at runtime: network timeout, user input invalid, file not found. Programmer errors are bugs: calling a function with wrong arguments, null reference. Custom errors should represent operational errors and can carry an isOperational: true flag.
Q7. Can a custom error have instanceof for both the parent and child class? > Yes. new ValidationError() instanceof ValidationError is true, and new ValidationError() instanceof AppError is also true if ValidationError extends AppError. And instanceof Error is true at the top.
Q8. How do you serialize a custom error to JSON for API responses? > By default, JSON.stringify(error) gives {} — Error properties are not enumerable. Add a toJSON() method: toJSON() { return { name: this.name, message: this.message, code: this.code }; }. Or use Object.assign({}, { name, message, ...custom props }).
Exam Focus
Revise definitions, diagrams, examples, and short-answer points for JavaScript Custom Errors – Extend Error Class, Custom Error Types & instanceof.
Interview Use
Prepare one clear explanation, one practical example, and one common mistake for this JavaScript Master Course topic.
Search Terms
javascript-complete-guide, javascript master course, javascript, complete, guide, error, handling, custom
Related JavaScript Master Course Topics