Learning on Web Dev Open is free for all.

Systems Thinking > Failure, deliberatelyWhere try/catch belongs
Phase 03Failure, deliberately148 of 434

Where try/catch belongs

Not everywhere. A catch block that logs and rethrows is noise; a catch block that swallows is a bug you will find in six months.

Concept12 minAI adversary

A catch block earns its place if it does one of three things: recovers, so execution genuinely continues on a sensible path; translates, adding context and rethrowing something more useful; or reports, at the outermost point where a human or a log will see it. If it does none of those, deleting it makes the code better, because an uncaught error at least stops.

The failure mode this prevents is the swallowed error: a catch that logs to console and carries on with undefined data, producing a symptom three functions away with no connection to the cause. Every debugging session that starts with "it just shows a blank page" ends at one of these.

Boundaries are where handling belongs: the request handler, the route, the job runner, the UI error boundary you will meet in Phase 04. Between the boundary and the failure, code should mostly not try to be clever, because the intermediate frames do not have the context to decide what should happen.

You should now be able to

  • Place a catch at a boundary rather than at a call site
  • Say what a catch block must do to earn its place
Ask the community

Loading…