Reviewing a catch formatter from its failure paths

Reviewing a catch formatter from its failure paths

●2 ●48
calendar_today ago • schedule2 min read
— Originally published at chriseugenerodriguez.com

Start with the failure cases, not the happy path. A catch variable may be an Error, but JavaScript also allows a thrown string, null, or a plain object. If a diagnostic helper assumes every caught value has a message property, its attempt to explain a failure can become a second failure.

Prerequisites are modest: TypeScript with useUnknownInCatchVariables enabled, plus a boundary where an operation is executed and failures are converted into a result the caller can consume. With that setting, the catch value is unknown. That is valuable because it prevents error-specific property access until the code has established the value’s runtime shape.

The implementation decision is to centralize classification in a formatter. First, recognize Error instances with instanceof Error. This is the branch where the standard message property can be used safely. Next, recognize a thrown string explicitly, because it is legal and often contains the only available diagnostic. Finally, return a generic description for every other value, including null, without probing arbitrary properties.

The expected result is a stable boundary contract. Normal operations return their value. Failed operations return a message instead of allowing the formatter to crash. An Error retains its diagnostic text, a string stays distinguishable from an Error, and an unknown value is reported conservatively. The supplied runtime assertions focus on those observable paths: Error, string, null, and a successful return.

One limitation remains essential in review: instanceof Error is classification, not validation of message quality or disclosure safety. A custom error can have an empty or internal-only message, and a plain object may contain useful metadata that this intentionally small formatter ignores. Add domain-specific branches only when the application has a clear contract for them; do not replace the fallback with speculative property access.

The compile-time setting and runtime behavior support different claims. The flag requires narrowing in source code. The formatter handles the values it receives at runtime. Keeping those responsibilities separate is what makes this small repair dependable.

Working example

// TypeScript counterpart: enable `useUnknownInCatchVariables: true`; then `err` is
// `unknown` here and must be narrowed before reading `err.message`.
// This runnable JavaScript demonstrates runtime behavior only; it does not prove
// TypeScript's compile-time narrowing.

/**
 * Converts any value that was thrown into a display-safe message.
 * @param {unknown} err
 * @returns {string}
 */
export function formatCaughtError(err) {
  if (err instanceof Error) {
    return `Error: ${err.message}`;
  }

  if (typeof err === 'string') {
    return `Thrown string: ${err}`;
  }

  return `Thrown non-Error value (${err === null ? 'null' : typeof err})`;
}

/**
 * Executes an operation at an exception boundary and formats any thrown value.
 * @param {() => unknown} operation
 * @returns {{ ok: true, value: unknown } | { ok: false, message: string }}
 */
export function runAndFormat(operation) {
  try {
    return { ok: true, value: operation() };
  } catch (err) {
    return { ok: false, message: formatCaughtError(err) };
  }
}

Read the full article: https://chriseugenerodriguez.com/blog/safely-handle-unknown-catch-variables

Want more #programming deep dives?

Join 5,982+ developers sharing real benchmarks, code breakdowns, and projects. Free forever.

1 Comment

0 votes

More Posts

A Message From Our Founder: On the Winding Down of LaaSy™

Ken W. Algerverified - Oct 29

I’m a Senior Dev and I’ve Forgotten How to Think Without a Prompt

Karol Modelski - Mar 19

Frameworks Are Institutional Memory

Ken W. Algerverified - Sep 17

TypeScript Complexity Has Finally Reached the Point of Total Absurdity

Karol Modelski - Apr 23

Your Tech Stack Isn’t Your Ceiling. Your Story Is

Karol Modelski - Apr 9
chevron_left
987 Points • 50 Badges
Santa Monica, CA • chriseugenerodriguez.com
37Posts
0Comments
8Connections
10 years fe

Related Jobs

View all jobs →

Commenters (This Week)

1 comment
1 comment

Contribute meaningful comments to climb the leaderboard and earn badges!