Your JS Error Is Lying to You
The article explains why logging a caught error with JSON.stringify often produces an empty object. The message and cause of an Error are non-enumerable properties[1], so JSON.stringify, Object.keys, the spread operator and Object.assign all skip them, although Object.getOwnPropertyNames still lists them.
The stack trace is not defined by the language[2]. In V8[3], the engine used by Node.js, it is recorded where the error is created rather than where it is thrown, it stops at 10 frames by default, and any code can overwrite it. Wrapping an error without passing cause loses the original failure, and even when cause is passed, the error cause chain[4] has to be walked, and it can loop back on itself. Other engines, such as Firefox, list different properties and stack formats for the same error.
A thrown value can be any JavaScript value, not necessarily an Error, so a catch block should check it before reading message. Structured clone, postMessage, worker threads and child-process IPC each keep a different part of an error, and none of them returns the original object. The author recommends always passing cause when wrapping, making retry decisions by error codes, and building log records with a function that follows every link between errors, logs only named fields and stops at a depth limit.
Read the original blog.gaborkoos.comDiscussion
Sources
-
blog.gaborkoos.com
Your JS Error Is Lying to You


