JavaScript's built-in Error hierarchy: **Error** (base), **TypeError** (wrong type), **RangeError** (out of range), **ReferenceError** (undefined variable), **SyntaxError** (invalid code), **URIError** (malformed URI). The **stack** property contains the full call stack trace — invaluable for debugging.
1Understanding Error Objects
JavaScript's built-in Error hierarchy: Error (base), TypeError (wrong type), RangeError (out of range), ReferenceError (undefined variable), SyntaxError (invalid code), URIError (malformed URI). The stack property contains the full call stack trace — invaluable for debugging.
In catch blocks, use instanceof to handle different error types differently: if (e instanceof TypeError) { ... }
// Built-in error types
try { null.property; } // TypeError
catch (e) { console.log(e instanceof TypeError, e.name); }
try { undefinedVar; } // ReferenceError
catch (e) { console.log(e instanceof ReferenceError, e.name); }
try { new Array(-1); } // RangeError
catch (e) { console.log(e instanceof RangeError, e.name); }2Practical Example
Here is a real-world application of Error Objects showing how it is used in production JavaScript code.
// Use instanceof for specific handling
function handleError(e) {
if (e instanceof TypeError) {
console.log('Type problem:', e.message);
} else if (e instanceof RangeError) {
console.log('Out of range:', e.message);
} else {
console.log('Unexpected error:', e.message);
throw e; // re-throw unknown errors
}
}3Best Practices
Follow these guidelines when working with Error Objects:
1. Use specific error types when possible (TypeError, RangeError)
2. Inspect e.stack in development for debugging
3. Use instanceof for type-specific error handling
Tip: In catch blocks, use instanceof to handle different error types differently: if (e instanceof TypeError) { ... }
// Built-in error types
try { null.property; } // TypeError
catch (e) { console.log(e instanceof TypeError, e.name); }
try { undefinedVar; } // ReferenceError
catch (e) { console.log(e instanceof ReferenceError, e.name); }
try { new Array(-1); } // RangeError
catch (e) { console.log(e instanceof RangeError, e.name); }