Error Propagation in JavaScript
See how errors move up through function calls in JavaScript: re-throw, wrap an error with context, chain causes and log in one place. Explanation and output.
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}
Sample Output
Level 2 caught: Error from level 3
There is no "Level 3 caught" line. level3 throws but has no catch of its own.
Caused by: Operation 2 failed
This is the original error, kept on the cause property of the new error.
In this one
- How an error travels up the call chain
- When to re-throw an error
- How to wrap an error with a clearer message
- How to keep the original error as a cause
How it works
- 1
level3 throws with no catch.
- 2
level2 catches, logs and re-throws.
- 3
level1 catches, logs and re-throws.
- 4
The top catch prints the final line.
- 5
processData wraps the JSON error.
- 6
operation1 wraps operation2 and keeps the cause.
How the error moves up
Follow the error from level3 to the top catch.
- 1.level1 calls level2, and level2 calls level3.
- 2.level3 throws "Error from level 3". It has no catch.
- 3.level2 catches it, logs it and re-throws.
- 4.level1 catches it, logs it and re-throws.
- 5.The top catch prints Final catch.
Edge cases
Swallowing errors
A catch logs nothing and does not re-throw, so the bug hides.
Either handle the error fully or throw it again.
Losing the original stack
A wrapped error shows only the new stack.
Keep the old error as cause so its stack is still there.
What's going on
When a function throws and does not catch the error, the error moves up to the function that called it. This is called propagation. It keeps going up until some catch handles it, or the program stops. JavaScript lets you choose where to catch, add context, or pass the error on.
Method 1 has three levels. level1 calls level2, and level2 calls level3. level3 only throws. It has no try, so it prints nothing. level2 catches the error, logs it, and throws it again. That is a re-throw. level1 does the same, and the final catch at the top prints the last line. So you see three lines, not four.
Re-throwing is useful when a level wants to log or clean up but cannot fix the problem.
Method 2 wraps the error. processData catches the low-level JSON error and throws a new Error with a clearer message. The new message tells you what the code was trying to do when it failed.
Method 3 keeps the original error as a cause. ChainedError stores the old error in this.cause, so you can read both messages. Modern JavaScript also supports new Error(message, { cause }) for the same idea.
Method 4 sends errors to one errorHandler function. Having one place for logging keeps the rules the same everywhere. In this sample riskyOperation is defined but never called, so it prints nothing. Call it inside a try to see "Error in riskyOperation : Operation failed".
Quiz
Tap an option. The answer stays hidden until you pick.
Question 1
How many lines does Method 1 print?
Pick an answer to check it.
Question 2
What does a re-throw do?
Pick an answer to check it.
Questions people ask
Should every function have try and catch?
No. Catch where you can do something useful, like showing a message.
What happens if no one catches the error?
The script stops at that point and the error shows in the console.
What is the cause option?
new Error("msg", { cause: err }) stores the earlier error on error.cause.