Skip to content
R.

How do I safely handle unknown catch variables with useUnknownInCatchVariables?

Treat catch variables as `unknown`, narrow them with `instanceof Error`, and keep a fallback so thrown strings or arbitrary values still produce a usable message without unsafe property access.

About 11 min readComments

A catch block is one of the few places in a TypeScript program where the code has to admit it does not fully know what it received. If the handler immediately reads `err.message`, it assumes every thrown value already looks like an `Error`. That is convenient until a string, a plain object, or `null` is thrown and the error formatter becomes the thing that fails.

`useUnknownInCatchVariables` is the feature that makes that uncertainty visible. Combined with a normal type guard such as `instanceof Error`, it forces the code to prove what it is handling before it uses error-specific properties. The result is a small but important change in shape: the catch boundary becomes explicit, the formatter stays safe, and the code can still report meaningful failures when the thrown value is not an `Error` at all.

Why the catch boundary is the real problem

The bug in this pattern is not that exceptions exist. The bug is that many error-formatting helpers quietly assume every thrown value already behaves like an `Error`, then reach straight for `.message`. That assumption works until the first thrown string, plain object, or `null` slips through the boundary and turns the formatter into a second failure. The result is especially confusing because the original problem has already been interrupted, and the diagnostic code now obscures it with its own crash.

TypeScript’s `useUnknownInCatchVariables` flag is useful precisely because it interrupts that habit. It changes the catch variable from a permissive shape into `unknown`, which forces the code to prove what was thrown before it reads error-specific properties. That is not ceremony; it is the point. An exception boundary is where the application loses certainty, so the type system should make that loss visible instead of letting unsafe property access pass as if every throw were well-formed.

The article’s example keeps the boundary small on purpose. One helper formats the thrown value, and one wrapper calls an operation inside a `try`/`catch`. That separation makes the tradeoff easy to see: the wrapper owns exception capture, while the formatter owns classification. The goal is not to invent a universal error model. It is to make the formatter honest enough to handle what JavaScript can actually throw.

main.mjs / javascript
// 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) };
  }
}

SourcesTypeScript Handbook: Narrowing (opens a new tab)TypeScript TSConfig: useUnknownInCatchVariables (opens a new tab)

What `instanceof Error` gives you, and what it does not

`instanceof Error` is the narrowest useful starting point because it matches the common case without pretending to prove everything. In TypeScript, a successful `instanceof` check is a type guard, so the code inside that branch can safely read `err.message` as an `Error` property. That is the difference between a stringly typed guess and a narrowed branch the compiler can follow. Once the branch is entered, the formatter can build a message from the actual error object instead of from a cast.

That still leaves an important boundary. `instanceof Error` tells you the value is an `Error` instance, not that it was thrown by a particular subsystem or contains a useful recovery hint. A network layer may wrap a timeout, a validation layer may use a custom subclass, and a third-party library may throw an `Error` with an empty message. The narrowing only guarantees the property exists. It does not promise that the message is meaningful, actionable, or safe to expose directly to users.

This is why the article keeps the fallback branch. If the value is not an `Error`, the helper should not pretend it knows more than it does. A thrown string can still be surfaced as a string, and an arbitrary value can still be identified as non-Error without probing its properties first. The useful lesson is not that `instanceof Error` solves exception handling. It is that it lets you take the obvious safe step before you decide what kind of fallback remains appropriate.

SourcesTypeScript Handbook: Narrowing (opens a new tab)

How the fallback keeps the formatter usable

A safe formatter needs two jobs, not one. First, it should preserve the useful message for real `Error` objects. Second, it should avoid turning non-Error values into a new runtime failure. The sample helper does this by checking for `Error`, then checking for `string`, and finally falling back to a generic description of the value’s kind. That keeps the output predictable while still reflecting the difference between a typed error and an arbitrary thrown value.

The fallback matters because JavaScript does not require `throw` to receive an `Error`. Code in the wild can throw a string, a number, an object, or even `null`. Without a fallback, the formatter would need to risk unsafe property access or swallow the original shape entirely. With the fallback, the code reports that something was thrown without claiming to know more than it does. That is a better failure mode for diagnostics, logs, and test output.

There is also a practical design benefit here. Callers do not need to know whether the formatter received an `Error`, a string, or something else. They receive a single message string and a success/failure shape from the wrapper. That does not mean every thrown value becomes equally meaningful. It means the system can continue to report failures consistently while reserving richer handling for the cases where the runtime type actually supports it.

SourcesTypeScript TSConfig: useUnknownInCatchVariables (opens a new tab)TypeScript Handbook: Narrowing (opens a new tab)

Why a compilation fix is not the same as runtime validation

`useUnknownInCatchVariables` is a compile-time guardrail, not a promise that every thrown value will suddenly become structured. The flag changes what the compiler permits inside the catch block; it does not change how JavaScript behaves at runtime. That distinction matters because the unsafe code pattern can still exist in plain JavaScript, and a TypeScript project can still receive values that are not `Error` objects from dependencies, browser APIs, or application code outside the current file.

The sample wrapper demonstrates that division clearly. The tests exercise the runtime behavior: one path throws an actual `Error`, one throws a string, one throws `null`, and one returns normally. Those tests prove the formatter is robust at the boundary, but they do not prove that the compiler would allow unsafe access if the narrowing were removed. That static guarantee comes from the flag and from the `instanceof` check, not from the Node test runner.

This separation is useful because it prevents overclaiming. A passing runtime test says the formatter did not crash on the observed inputs. It does not say the code is impossible to misuse. A TypeScript narrowing says the code must justify property access before using it. Together they solve different parts of the same problem, and the article keeps both parts visible instead of blending them into one vague “it works” story.

SourcesTypeScript Handbook: Narrowing (opens a new tab)

Edge cases that still deserve thought

Two common edge cases deserve explicit mention. The first is a thrown string, which is legal JavaScript but easy to forget because many codebases treat `Error` as the only expected thrown type. A formatter that only knows `Error` objects either crashes or lies about the input. The second is an arbitrary thrown value such as `null` or a plain object. In both cases, the safe response is not to inspect `.message` first and hope for the best. It is to classify the value conservatively and keep going.

A third boundary is custom error classes. `instanceof Error` will include subclasses, which is usually what you want if the subclass follows the normal `Error` inheritance model. But this does not guarantee the message is user-ready. Some libraries put internal codes in the message, some intentionally leave messages brief, and some attach extra context on custom properties. If the article’s goal is human-readable diagnostics, that formatting policy still belongs in application code after the narrowing step.

There is also a limit to what the flag can help with when the code intentionally wants broader behavior. Sometimes a catch block only needs to log that something failed, not render a polished message. Even then, the narrowing rule is still useful because it makes the choice explicit. You either prove the value is an `Error`, branch on a different shape, or accept a fallback. The important part is that the decision happens in code instead of being hidden behind an unsafe property read.

SourcesTypeScript TSConfig: useUnknownInCatchVariables (opens a new tab)TypeScript Handbook: Narrowing (opens a new tab)

The smallest repair that holds up in real code

The most useful repair is also the smallest one: make the catch variable `unknown`, narrow it with `instanceof Error`, and keep a conservative fallback for everything else. That pattern avoids unsafe property access, keeps the formatter simple, and still preserves the original failure signal as a string. It does not force every application to adopt a large error hierarchy or a shared serialization format before it can print a useful diagnostic.

That modest scope is part of the point. If the code later needs richer error metadata, it can add a second branch for a custom error shape or a separate formatter for domain-specific exceptions. But those additions should come after the basic boundary is correct. A helper that can safely format a regular `Error`, a thrown string, and an arbitrary value is already better than one that assumes the catch variable has `.message` and fails again while trying to explain the first failure.

The article’s tests establish that this boundary is respected for the runtime inputs the helper actually sees. The TypeScript flag establishes that the unsafe assumption is no longer silently accepted in the source. That combination is the useful answer for a reader who is trying to make exception handling safer without overengineering it. The code stays ordinary JavaScript in shape, but the type system stops it from pretending every thrown value is the same thing.

main.test.mjs / javascript
import test from 'node:test';
import assert from 'node:assert/strict';
import { runAndFormat } from './main.mjs';

test('formats a real Error after narrowing with instanceof Error', () => {
  const result = runAndFormat(() => {
    throw new Error('database unavailable');
  });

  assert.deepEqual(result, {
    ok: false,
    message: 'Error: database unavailable',
  });
});

test('formats a string that was thrown instead of reading .message', () => {
  const result = runAndFormat(() => {
    throw 'connection reset';
  });

  assert.deepEqual(result, {
    ok: false,
    message: 'Thrown string: connection reset',
  });
});

test('uses a safe fallback for an arbitrary null thrown value', () => {
  const result = runAndFormat(() => {
    throw null;
  });

  assert.deepEqual(result, {
    ok: false,
    message: 'Thrown non-Error value (null)',
  });
});

test('returns the operation result when nothing is thrown', () => {
  const result = runAndFormat(() => 42);

  assert.deepEqual(result, { ok: true, value: 42 });
});

SourcesTypeScript TSConfig: useUnknownInCatchVariables (opens a new tab)TypeScript Handbook: Narrowing (opens a new tab)

Share LinkedIn Email Subscribe

Discussion

Leave a comment

Comments appear after review. No email needed.

Image preview

Follow the blog

Choose email updates or your favorite RSS reader.

The weekly email

New articles on code, design, and AI. Fridays, only when there is something new.

By subscribing, you agree to weekly blog emails.
Confirm in your inbox. Unsubscribe anytime. Privacy

Use OpenRSS

Preview the feed, then choose a reader to subscribe.

Open in OpenRSS (opens a new tab)

Already have a reader?

Paste this link into your reader's Add feed option.

Prefer a reader? RSS does not require an email address. View XML feed