Coding Techniques
Error Handling · Study material
Serialising errors for logs and APIs
An error's name, message and stack are not enumerable, so JSON.stringify(error) prints {}. Copy the fields you need into a plain object:
const err = new TypeError("price must be a number", { cause: "bad input" });
console.log(JSON.stringify(err)); // message, name and stack are not enumerable
function toJSONSafe(e) {
return { name: e.name, message: e.message, cause: e.cause ?? null };
}
console.log(JSON.stringify(toJSONSafe(err)));
{}
{"name":"TypeError","message":"price must be a number","cause":"bad input"}The [error, value] pattern
Where failure is normal (parsing user input, optional files), returning the error as a value keeps the happy path flat and forces the caller to look at it:
// Return [error, value] instead of throwing – handy where failure is expected
function attempt(fn, ...args) {
try {
return [null, fn(...args)];
} catch (e) {
return [e, undefined];
}
}
const [err1, data] = attempt(JSON.parse, '{"ok":true}');
const [err2] = attempt(JSON.parse, "not json");
console.log(err1, data);
console.log(err2.name);
null { ok: true }
SyntaxErrorWhich tool for which failure?
| Situation | Approach |
|---|---|
| A bug (impossible state) | throw and let it crash loudly / log it |
| Invalid user input | custom ValidationError or a returned error list |
| Expected, frequent failure | return a result ([err, value], null, default) |
| Low-level error at a higher level | wrap with { cause } |
| Several independent failures | AggregateError / allSettled |
| Cleanup (close, unlock, hide spinner) | finally |
| Async failure | await in try/catch, or .catch |
Error-handling checklist
- Throw Error objects with clear messages.
- Give custom errors a name and useful fields.
- Catch specific types; re-throw the rest.
- Never leave a catch block empty – at least log.
- Put cleanup in finally.
- Keep the original error as cause when wrapping.
- Handle every promise: await + try/catch or .catch.
- Show users friendly messages, log technical details.