Skip to main content

How to Rethrow an Error in JavaScript

· 5 min read
Jagdish Kumawat
Founder @ Dewiride

A catch block catches every error, including the ones you didn't plan for. Handle the error you expected and send every other one back up with throw err;, so a real bug still stops the program and shows you where it happened.

Syntax​

Syntax
try {
<code that may fail>
} catch (err) {
if (!(err instanceof <ExpectedError>)) {
throw err;
}
<handle the expected error>
}
PartWhat it does
err instanceof <ExpectedError>true when the error is the kind this block knows how to handle.
!( ... )Turns that around: true for every other kind.
throw err;Sends the same error on, as if there were no catch here.

MDN's throw reference: "Execution of the current function will stop (the statements after throw won't be executed), and control will be passed to the first catch block in the call stack. If no catch block exists among caller functions, the program will terminate."

The Example​

The example reads settings from text. When the text isn't valid JSON, it falls back to default settings. When something else goes wrong, here a value that isn't text at all, it rethrows.

Prerequisites​

  • Node.js. This guide uses Node.js 26.13.1.

Step 1: Write the Code​

Create a file named main.js:

main.js, which defines readSettings(text) that returns JSON.parse(text), rethrows any error that isn't a SyntaxError and otherwise prints Not valid JSON, so the defaults are used. and returns theme light; it is called with valid JSON, with the word dark and with a Symbol.

main.js
function readSettings(text) {
try {
return JSON.parse(text);
} catch (err) {
if (!(err instanceof SyntaxError)) {
throw err;
}
console.log('Not valid JSON, so the defaults are used.');
return { theme: 'light' };
}
}

console.log(readSettings('{"theme": "dark"}'));
console.log(readSettings('dark'));
console.log(readSettings(Symbol('dark')));
  • Valid JSON is returned as an object.
  • 'dark' isn't valid JSON, so JSON.parse throws a SyntaxError: expected, handled, defaults returned.
  • Symbol('dark') can't be turned into text, so JSON.parse throws a TypeError: not expected, so it's rethrown.

Step 2: Run It​

Terminal
node main.js
Output
{ theme: 'dark' }
Not valid JSON, so the defaults are used.
{ theme: 'light' }
/Users/Shared/you/main.js:6
throw err;
^

TypeError: Cannot convert a Symbol value to a string
at JSON.parse (<anonymous>)
at readSettings (/Users/Shared/you/main.js:3:17)
at Object.<anonymous> (/Users/Shared/you/main.js:15:13)
at Module._compile (node:internal/modules/cjs/loader:1968:14)
at Object..js (node:internal/modules/cjs/loader:2108:10)
at Module.load (node:internal/modules/cjs/loader:1690:32)
at Module._load (node:internal/modules/cjs/loader:1480:12)
at wrapModuleLoad (node:internal/modules/cjs/loader:261:19)
at Module.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:171:5)
at node:internal/main/run_main_module:33:47

Node.js v26.13.1

A zsh terminal where node main.js prints the dark theme, the defaults message and the light theme, then stops with TypeError: Cannot convert a Symbol value to a string, thrown again at line 6.

The first two calls behaved as planned. The third stopped the program with the original TypeError, and its stack trace still points at the call on line 15 and at JSON.parse, because throw err passed on the same error object. The command is the same in zsh, bash and PowerShell.

Adding Context with cause​

Sometimes you want to rethrow with a clearer message without losing the original. Pass it as cause:

Wrap the error, keep the original
throw new Error('Settings file is broken', { cause: err });

The new error's cause property holds the original: in my check, err.cause instanceof SyntaxError was true.

Common Mistakes​

MistakeWhat happensDo this instead
A catch that handles every error the same wayBugs, such as a TypeError, are hidden behind the fallbackRethrow what you didn't expect
Rethrowing with throw new Error(err.message)The original type and stack trace are lostUse throw err, or new Error(..., { cause: err })
Forgetting the parentheses in !(err instanceof X)!err is evaluated first, so the check is always falseWrap the whole instanceof test in parentheses

Troubleshooting​

SymptomLikely causeFix
The program falls back to defaults when it shouldn'tThe catch doesn't rethrow other errorsAdd the instanceof check and throw err
A crash points at throw err;An unexpected error was rethrown, as designedRead the error below that line: it's the original problem

FAQ​

Does rethrowing change the stack trace?​

No. throw err throws the same error object, and its stack trace was recorded when it was first created.

Can I rethrow from an async function?​

Yes. The function's promise is rejected with that error, and the caller's await throws it again.

Conclusion​

Check the error's type in catch, handle the kind you expected and throw err for the rest. Fallbacks stay for real fallbacks, and bugs still surface with their original stack trace.

Additional Resources​