Lab 07: Error Handling Patterns
Overview
Step 1: Error Types
// Built-in Error types
try { null.property; }
catch (e) {
console.log(e instanceof TypeError); // true
console.log(e.name); // 'TypeError'
console.log(e.message);
console.log(e.stack.split('\n')[0]); // Error location
}
// RangeError
try { new Array(-1); }
catch (e) { console.log(e instanceof RangeError, e.message); }
// SyntaxError (usually from eval/JSON.parse)
try { JSON.parse('not json'); }
catch (e) { console.log(e instanceof SyntaxError, e.message.slice(0, 30)); }
// URIError
try { decodeURIComponent('%'); }
catch (e) { console.log(e instanceof URIError, e.name); }
// ReferenceError
try { undeclaredVariable; }
catch (e) { console.log(e instanceof ReferenceError); }Step 2: Custom Error Classes
Step 3: try/catch/finally
Step 4: Error Chaining (cause)
Step 5: Promise Rejection Handling
Step 6: Result / Either Pattern
Step 7: Global Error Handling
Step 8: Capstone — Error Chain Demo
Summary
Pattern
When to Use
Pros
Last updated
