Lab 07: Error Handling Patterns

Time: 30 minutes | Level: Practitioner | Docker: docker run -it --rm node:20-alpine sh

Overview

Master error handling: built-in error types, custom errors, try/catch/finally, error chaining with cause, Promise rejection handling, unhandledRejection, and the Result/Either pattern.


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

💡 finally always runs even if you return inside try or catch. The return value from finally overrides others.


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

Run verification:

📸 Verified Output:


Summary

Pattern
When to Use
Pros

Custom Error class

Domain-specific errors

Rich metadata, instanceof checks

Error chaining (cause)

Wrapping lower-level errors

Full context preserved

try/catch/finally

Synchronous + async/await

Standard, familiar

.catch()

Promise chains

Inline error handling

Result pattern

When errors are expected

No exceptions, explicit flow

unhandledRejection

Global safety net

Catch forgotten rejections

uncaughtException

Last resort

Prevent silent crashes

Last updated