Error Propagation in JavaScript
Propagate errors through call stack
IntermediateError HandlingExample 3 of 10
error-propagation.js
1// Method 1: Re-throw error2function level1() {3 try {4 level2();5 } catch (error) {6 console.error('Level 1 caught:', error.message);7 throw error; // Re-throw8 }9}1011function level2() {12 try {13 level3();14 } catch (error) {15 console.error('Level 2 caught:', error.message);16 throw error; // Re-throw17 }18}1920function level3() {21 throw new Error('Error from level 3');22}2324try {25 level1();26} catch (error) {27 console.error('Final catch:', error.message);28}2930// Method 2: Wrap error31function processData(data) {32 try {33 return JSON.parse(data);34 } catch (error) {35 throw new Error(`Failed to process data: ${error.message}`);36 }37}3839try {40 processData('invalid');41} catch (error) {42 console.error('Wrapped error:', error.message);43}4445// Method 3: Error chain46class ChainedError extends Error {47 constructor(message, cause) {48 super(message);49 this.cause = cause;50 this.name = 'ChainedError';51 }52}5354function operation1() {55 try {56 operation2();57 } catch (error) {58 throw new ChainedError('Operation 1 failed', error);59 }60}6162function operation2() {63 throw new Error('Operation 2 failed');64}6566try {67 operation1();68} catch (error) {69 console.error('Chained error:', error.message);70 console.error('Caused by:', error.cause.message);71}7273// Method 4: Error handling middleware74function errorHandler(error, context) {75 console.error('Error in', context, ':', error.message);76 // Log to service, send notification, etc.77}7879function riskyOperation() {80 try {81 throw new Error('Operation failed');82 } catch (error) {83 errorHandler(error, 'riskyOperation');84 throw error;85 }86}
Output
Level 3 caught: Error from level 3 Level 2 caught: Error from level 3 Level 1 caught: Error from level 3 Final catch: Error from level 3 Wrapped error: Failed to process data: Unexpected token i in JSON at position 0 Chained error: Operation 1 failed Caused by: Operation 2 failed Error in riskyOperation : Operation failed
What's going on
Error propagation moves errors up call stack.
Re-throwing
Catch and re-throw
Preserve original error
Add context if needed
Wrapping Errors
Wrap in new error
Add context
Preserve original
Error Chains
Link errors
Track cause
Full error history
Error Middleware
Centralized handling
Logging
Notifications
Best Practices
Re-throw when appropriate
Add context
Don't swallow errors
Log properly