Curriculum
Concept 78 // Module 08: Advanced JavaScript & Metaprogramming
Error Objects, Custom Errors & Error.isError()
Module 08: Advanced JavaScript & Metaprogramming•Concept 78 of 100• 5 min read
Error Objects, Custom Errors & Error.isError()
JavaScript provides a built-in **Error** object and the **try...catch...finally** block to handle runtime exceptions gracefully without crashing the entire application.
The Core Concept
Syntax Reference
// 1. Throwing an Error
throw new Error("Something went wrong");
// 2. Handling Errors
try {
// Code that might fail
} catch (err) {
// Handle the error
console.log(err.name, err.message);
} finally {
// Always runs
}
// 3. Custom Errors
class MyError extends Error { ... }
Live Interactive Studio
JavaScript has specific built-in error types. Using `instanceof` allows you to handle different failures in different ways.
JavaScript Editor
Loading...
Console Output
Waiting for output...
Key Code Patterns in Action
01
Specific Error Types
// 1. Specific Error Types
try {
// decodeURIComponent("%"); // ❌ URIError
// const x = y; // ❌ ReferenceError
// JSON.parse("{bad}"); // ❌ SyntaxError
} catch (err) {
if (err instanceof ReferenceError) {
console.log("Missing variable!");
} else {
console.log("General error:", err.message);
}
}JavaScript has specific built-in error types. Using `instanceof` allows you to handle different failures in different ways.
02
Re-throwing Errors
// 2. Re-throwing Errors
function process() {
try {
throw new Error("Database Fail");
} catch (err) {
console.log("Logging error internally...");
throw err; // Send it up to the caller
}
}
try {
process();
} catch (e) {
console.log("Caller caught:", e.message);
}Sometimes you want to log an error but still let the calling function know that something went wrong.
03
The Power of Finally
// 3. The Power of Finally
function test() {
try {
return "Result";
} finally {
console.log("Cleanup complete");
}
}
console.log(test());Even if you `return` from inside the `try` block, the `finally` block **is guaranteed to run**. This is essential for closing files or database connections.
04
1. Core Usage: Error Objects, Custom Errors & Error.isError()
// Core syntax and usage for Error Objects, Custom Errors & Error.isError()
const feature = 'error-objects-custom-errors-error-iserror';
console.log('Concept 78:', feature);
console.log('Active:', true);Illustrates the fundamental invocation and syntax structure for Error Objects, Custom Errors & Error.isError().
05
2. Defensive Handling & Edge Case
// Edge-case defensive handling
function handleSafe(input) {
if (input === null || input === undefined) return 'safe-fallback';
return String(input).trim();
}
console.log(handleSafe('error-objects-custom-errors-error-iserror'));
console.log(handleSafe(null));Shows how to write defensive, safe JavaScript code that handles nullish or unexpected inputs when working with Error Objects, Custom Errors & Error.isError().
06
3. Clean Architecture & Production Pattern
// Production-grade pattern for Error Objects, Custom Errors & Error.isError()
const settings = Object.freeze({
id: 'error-objects-custom-errors-error-iserror',
ready: true,
timestamp: Date.now()
});
console.log('Settings initialized:', settings.id, settings.ready);Demonstrates clean, immutable production code avoiding unintended state mutations.
Real-World Engineering Takeaways
Network Requests: Handling timeouts or 404/500 responses from APIs.
JSON Parsing: Safely parsing user-provided strings.
Form Input: Validating data before sending it to a server.
Third-party Libraries: Protecting your app from bugs in external dependencies.
Under the Hood: Engine & Memory Mechanics
How JavaScript Executes This
### **Errors & The Stack**
**1. Stack Traces:**
- When an Error object is created, it captures the current state of the **Call Stack**.
- This 'trace' is stored as a string in the `stack` property in the **Heap**.
**2. Exception Propagation:**
- If an error isn't caught, it "bubbles up" the **Call Stack**.
- Each frame is popped until a `catch` block is found.
- If none is found, the engine terminates and prints the stack trace to the console.
**3. Performance:**
- Creating and throwing errors is relatively expensive (due to stack capture).
- **Rule:** Use Errors for *exceptional* cases, not for regular control flow (like `if/else`).
Quick Knowledge Check
Test your understanding on these 10 questions (one by one):
Score: 0 / 10
Question 1 of 10 • Core Purpose & Mental Model
What is the core purpose of Error Objects, Custom Errors & Error.isError() in JavaScript?
// Concept 78: Error Objects, Custom Errors & Error.isError()
// Understanding the core mental model1 / 10