asyncfunctionloadUserData(userId){try{const res =awaitfetch(`/api/users/${userId}`);returnawait res.json();}catch(err){thrownewError("Failed to load user data",{ cause: err });}}try{awaitloadUserData(42);}catch(err){console.error(err.message);// "Failed to load user data"console.error(err.cause?.message);// original error message}
Note The cause option (ES2022) lets you wrap errors while preserving the original. Essential for debugging errors that propagate through layers.
// TypeError - wrong type for an operationtry{null.toString();}catch(e){console.log(e.constructor.name);}// "TypeError"// RangeError - value out of allowed rangetry{newArray(-1);}catch(e){console.log(e.constructor.name);}// "RangeError"// ReferenceError - undeclared variabletry{console.log(undeclaredVar);}catch(e){console.log(e.constructor.name);}// "ReferenceError"
Note Catching specific types helps you handle known errors differently from unexpected ones. AggregateError wraps multiple errors (used by Promise.any()).
// Browser global handlerwindow.addEventListener("unhandledrejection",(event)=>{console.error("Unhandled rejection:", event.reason);
event.preventDefault();// prevents console errorreportToService(event.reason);});// Node.js global handlerprocess.on("unhandledRejection",(reason, promise)=>{console.error("Unhandled rejection at:", promise,"reason:", reason);});
Note Global handlers are your safety net -- they should log and report, not silently swallow errors. Always prefer local try/catch for known async operations.
unhandled rejectionglobal error handlercatch all errorserror reporting
Working with Stack Traces
Syntax
error.stack
error.message
error.name
Example
functiondeepFunction(){thrownewError("Something broke");}try{deepFunction();}catch(err){console.log(err.name);// "Error"console.log(err.message);// "Something broke"console.log(err.stack);// Full stack trace string}
Note err.stack is not standardized but is supported everywhere in practice. It includes the error message and the call chain leading to where the error was created.