Error chaining in JavaScript: cleaner debugging with Error.cause - Matt Smith
Briefly

Error chaining in JavaScript: cleaner debugging with Error.cause - Matt Smith
"When you're working with layered code (e.g., services calling services, wrapper functions, bubbling errors, etc.), it's easy to lose track of what actually broke. Traditionally, you might write something like this: try { JSON.parse('{ bad json }'); } catch (err) { throw new Error('Something went wrong: ' + err.message); } Sure, you wrapped the error, but you've lost the original stack trace and error type."
"By using the parameter, you can preserve the original error cleanly: try { try { JSON.parse('{ bad json }'); } catch (err) { throw new Error('Something went wrong', { cause: err }); } } catch (err) { console.error(err.stack); console.error('Caused by:', err.cause.stack); } Here's what happens when you use Error.cause (notice how you can access both stack traces): Error: Something went wrong at ... Caused by: SyntaxError: Unexpected token b in JSON at position 2 at JSON.parse (<anonymous>) at ..."
Layered JavaScript code commonly loses the original error type and stack trace when errors are wrapped and re-thrown. Error.cause attaches the original error as a non-enumerable property to a new Error, preserving the root-cause error and its stack. Examples show nesting a JSON.parse failure and re-throwing with { cause: err }, then accessing both err.stack and err.cause.stack to inspect both traces. The cause property is non-enumerable like message and stack, so it does not clutter logs or for...in loops. JavaScript does not automatically merge stack traces, so each stack remains separate.
Read at Allthingssmitty
Unable to calculate read time
[
|
]