Error Propagation in JavaScript

Propagate errors through call stack

IntermediateError HandlingExample 3 of 10
error-propagation.js
1// Method 1: Re-throw error
2function level1() {
3 try {
4 level2();
5 } catch (error) {
6 console.error('Level 1 caught:', error.message);
7 throw error; // Re-throw
8 }
9}
10
11function level2() {
12 try {
13 level3();
14 } catch (error) {
15 console.error('Level 2 caught:', error.message);
16 throw error; // Re-throw
17 }
18}
19
20function level3() {
21 throw new Error('Error from level 3');
22}
23
24try {
25 level1();
26} catch (error) {
27 console.error('Final catch:', error.message);
28}
29
30// Method 2: Wrap error
31function processData(data) {
32 try {
33 return JSON.parse(data);
34 } catch (error) {
35 throw new Error(`Failed to process data: ${error.message}`);
36 }
37}
38
39try {
40 processData('invalid');
41} catch (error) {
42 console.error('Wrapped error:', error.message);
43}
44
45// Method 3: Error chain
46class ChainedError extends Error {
47 constructor(message, cause) {
48 super(message);
49 this.cause = cause;
50 this.name = 'ChainedError';
51 }
52}
53
54function operation1() {
55 try {
56 operation2();
57 } catch (error) {
58 throw new ChainedError('Operation 1 failed', error);
59 }
60}
61
62function operation2() {
63 throw new Error('Operation 2 failed');
64}
65
66try {
67 operation1();
68} catch (error) {
69 console.error('Chained error:', error.message);
70 console.error('Caused by:', error.cause.message);
71}
72
73// Method 4: Error handling middleware
74function errorHandler(error, context) {
75 console.error('Error in', context, ':', error.message);
76 // Log to service, send notification, etc.
77}
78
79function 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