---
title: "Error handling in TypeScript: unknown in catch, Error.cause and Result types"
description: "Learn why TypeScript types caught errors as unknown, how to narrow them safely, how to chain errors with Error.cause, and when a Result type beats throwing."
url: https://www.danny.engineering/article/error-handling-in-typescript-unknown-in-catch-errorcause-and-result-types
author: Danny
published: 2026-12-06T00:00:00.000Z
updated: 2026-12-02T12:56:00.000Z
tags: ["Typescript"]
---

# Error handling in TypeScript: unknown in catch, Error.cause and Result types

TypeScript is good at telling you what a function returns. It is much quieter about what a function might throw. A call can fail in a dozen ways, and none of them show up in its signature. Then, when you catch the failure, the compiler hands you a value of type `unknown` and leaves you to work out what it is.


This article is for developers who write TypeScript every day and want a clear, consistent way to deal with errors. We will start with why `catch` gives you `unknown`, move on to narrowing and custom error classes, chain errors together with `Error.cause`, and finish with Result types for failures you expect to happen.


## Why catch gives you unknown


In JavaScript you can throw anything. A string, a number, `null`, a plain object or a real `Error` are all valid.


```typescript
throw "something went wrong";
throw { code: 42 };
throw new Error("something went wrong");
```


Because of this, TypeScript cannot know what lands in a `catch` clause. For years it typed the variable as `any`, which meant you could write `err.message` and the compiler would happily let you, even if `err` was a string.


TypeScript 4.4 added the `useUnknownInCatchVariables` option, and it is switched on by `strict`. With it, the catch variable is `unknown`.


```typescript
try {
  JSON.parse(input);
} catch (err) {
  console.log(err.message);
  // Error: 'err' is of type 'unknown'.
}
```


This feels annoying at first, but it is honest. The compiler is telling you that you have not checked yet. Leave the option on, and learn the few patterns that make `unknown` easy to work with.


## Narrowing what you caught


The most common check is `instanceof Error`.


```typescript
try {
  JSON.parse(input);
} catch (err) {
  if (err instanceof Error) {
    console.error(err.message);
  } else {
    console.error("Unknown error", err);
  }
}
```


This works well in most code. It has one weak spot: an error created in a different realm, such as an iframe or a Node `vm` context, has a different `Error` constructor, so `instanceof` returns false.


The newer `Error.isError()` method fixes that. It checks whether a value is a genuine error object, whatever realm it came from. It is part of ECMAScript 2026 and works in current Chrome, Edge and Firefox, but Safari support is still only partial and it is not Baseline yet. For now, treat it as a nice extra rather than something to depend on in browser code.


In practice, a small helper that turns any thrown value into an `Error` covers most needs.


```typescript
export function toError(value: unknown): Error {
  if (value instanceof Error) return value;
  if (typeof value === "string") return new Error(value);
  try {
    return new Error(JSON.stringify(value));
  } catch {
    return new Error(String(value));
  }
}

try {
  await saveDraft(draft);
} catch (err) {
  const error = toError(err);
  logger.error(error.message, { stack: error.stack });
}
```


Notice the bare `catch` with no variable in the helper. Optional catch binding has been part of JavaScript since ES2019, and it is the clearest way to say you do not care what was thrown.


## Custom error classes


When callers need to react differently to different failures, a custom class gives them something solid to check.


```typescript
export class NotFoundError extends Error {
  readonly resource: string;

  constructor(resource: string, options?: ErrorOptions) {
    super(`${resource} was not found`, options);
    this.name = "NotFoundError";
    this.resource = resource;
  }
}

export class ValidationError extends Error {
  readonly field: string;

  constructor(field: string, message: string, options?: ErrorOptions) {
    super(message, options);
    this.name = "ValidationError";
    this.field = field;
  }
}
```


A few details matter here:

- **Set** **`name`****.** Stack traces and many logging tools print it. Without it, every error says `Error`.
- **Accept** **`ErrorOptions`** **and pass it to** **`super`****.** This is what lets callers attach a cause, which we cover next.
- **Declare fields explicitly.** Parameter properties such as `constructor(readonly field: string)` are not allowed under `erasableSyntaxOnly`, so plain field declarations keep the class compatible with Node's type stripping.

You may have seen advice to call `Object.setPrototypeOf(this, new.target.prototype)` in error subclasses. That was only needed when compiling to ES5. With any modern target, `instanceof NotFoundError` works without it.


Now the caller can branch on the type:


```typescript
try {
  const post = await getPost(slug);
  return render(post);
} catch (err) {
  if (err instanceof NotFoundError) {
    return renderNotFound();
  }
  throw err;
}
```


The last line is important. If you catch something you do not know how to handle, throw it again. Swallowing unknown errors is how bugs hide for months.


## Chaining errors with Error.cause


Low-level errors are often too vague to be useful on their own. `ECONNREFUSED` tells you a connection failed, but not which part of your app was trying to do what. The usual fix used to be building a new message and losing the original stack.


`Error.cause`, added in ES2022, lets you wrap an error and keep the original attached.


```typescript
async function loadUser(id: string) {
  try {
    const res = await fetch(`https://api.example.com/users/${id}`);
    if (!res.ok) {
      throw new Error(`Request failed with ${res.status}`);
    }
    return await res.json();
  } catch (err) {
    throw new Error(`Could not load user ${id}`, { cause: err });
  }
}
```


The new error describes the failure in terms of your app. The original is still there on `error.cause`. Node prints the whole chain when an error is logged or goes uncaught, and browser devtools show it too, so you get both the high-level story and the root stack trace.


To use the second argument in TypeScript, your `lib` setting needs to include `es2022` or later. Any `target` of `es2022` or higher includes it by default.


The type of `cause` is `unknown`, for the same reason the catch variable is. When you walk the chain, narrow as you go.


```typescript
function describe(error: unknown): string[] {
  const lines: string[] = [];
  let current: unknown = error;

  while (current instanceof Error) {
    lines.push(`${current.name}: ${current.message}`);
    current = current.cause;
  }

  return lines;
}

// ["Error: Could not load user 7", "TypeError: fetch failed", "Error: connect ECONNREFUSED ..."]
```


A good rule: wrap an error when you cross a boundary where the meaning changes, such as from "the network failed" to "we could not load the user". Do not wrap at every function call, or your logs fill up with five layers saying the same thing.


## Result types for expected failures


Exceptions are a good fit for things that should not happen: bugs, broken invariants, a database that has vanished. They are a poor fit for failures you fully expect, such as a form field that fails validation or a user that does not exist. In those cases the failure is a normal outcome, and hiding it in an invisible throw makes it easy to forget.


A Result type makes the failure part of the return value, so the compiler forces callers to deal with it. You do not need a library. A discriminated union is enough.


```typescript
export type Result<T, E = Error> =
  | { ok: true; value: T }
  | { ok: false; error: E };

export const ok = <T>(value: T): Result<T, never> => ({ ok: true, value });
export const err = <E>(error: E): Result<never, E> => ({ ok: false, error });
```


Here is a function that parses a port number from configuration:


```typescript
type PortError =
  | { kind: "missing" }
  | { kind: "not-a-number"; raw: string }
  | { kind: "out-of-range"; port: number };

function parsePort(raw: string | undefined): Result<number, PortError> {
  if (raw === undefined) return err({ kind: "missing" });

  const port = Number(raw);
  if (!Number.isInteger(port)) return err({ kind: "not-a-number", raw });
  if (port < 1 || port > 65535) return err({ kind: "out-of-range", port });

  return ok(port);
}
```


The caller has to check `ok` before it can touch `value`:


```typescript
const result = parsePort(process.env.PORT);

if (!result.ok) {
  switch (result.error.kind) {
    case "missing":
      console.error("PORT is not set");
      break;
    case "not-a-number":
      console.error(`PORT must be a number, got "${result.error.raw}"`);
      break;
    case "out-of-range":
      console.error(`PORT ${result.error.port} is out of range`);
      break;
  }
  process.exit(1);
}

startServer(result.value); // result.value is number here
```


Two things are worth pointing out. First, the error type is a union of plain objects rather than classes. That keeps it serialisable and lets `switch` narrow each case. Second, if you add a new kind of `PortError`, you can make the compiler flag every `switch` that does not handle it by adding a `default` branch that assigns `result.error` to a variable of type `never`.


## Wrapping code that throws


Most of the libraries you use will still throw. A small helper turns a promise that may reject into a Result, so you can keep the rest of your code consistent.


```typescript
export async function attempt<T>(promise: Promise<T>): Promise<Result<T>> {
  try {
    return ok(await promise);
  } catch (e) {
    return err(toError(e));
  }
}

const result = await attempt(fetch("https://api.example.com/health"));

if (!result.ok) {
  console.error("Health check failed", result.error);
} else {
  console.log("Status", result.value.status);
}
```


This is where `toError` from earlier pays off. Whatever the library threw, the Result always holds a real `Error`.


## Putting it together


In a real codebase you will use all three tools, each in its place:

- **Throw** for bugs and for failures nobody near the call can handle. Let them travel up to a top-level handler, an error boundary or a framework error page.
- **Wrap with** **`cause`** when an error crosses a layer and needs a clearer message, without losing the original.
- **Return a Result** for expected outcomes the immediate caller must handle, such as validation, parsing and "not found" lookups.

The edges of your app are where these meet. A route handler might call a service that returns a Result, turn an `ok: false` into a 400 response, and let anything thrown fall through to the framework's 500 handling.


```typescript
export async function POST(request: Request) {
  const body = await request.json().catch(() => null);
  const result = validateSignup(body);

  if (!result.ok) {
    return Response.json({ errors: result.error }, { status: 400 });
  }

  await createAccount(result.value); // throws only if something is truly broken
  return Response.json({ ok: true }, { status: 201 });
}
```


## Version support

- `unknown` in catch clauses arrived in TypeScript 4.4 and is on whenever `strict` is on, including in TypeScript 6.
- `Error.cause` and the `ErrorOptions` argument are ES2022. They work in every current browser and in all supported Node versions. TypeScript needs `lib` to include `es2022` or later.
- `Error.isError()` is ES2026. It works in current Chrome, Edge and Firefox, but Safari support is partial, so check before relying on it in browser code.
- Discriminated unions and the Result pattern are plain types. They work in any TypeScript version and have no runtime cost beyond the small objects you create.

## When not to use it


Result types are useful, but they are not free. Skip them when:

- **Nobody nearby can handle the failure.** Passing a Result up through six layers that just return it again is worse than a throw that travels on its own.
- **The failure is a bug.** A missing environment variable at startup, or an impossible state in a reducer, should crash loudly. Returning it as data invites someone to ignore it.
- **You are working with a framework that expects throws.** Next.js `notFound()` and `redirect()`, React error boundaries and many test runners all rely on thrown values. Fighting that convention adds friction for little gain.
- **The team has not agreed on it.** A codebase where half the functions throw and half return Results, with no clear rule, is harder to read than one that only throws.

And avoid wrapping with `cause` at every level. One or two meaningful layers is plenty.


## Wrapping up

- Keep `useUnknownInCatchVariables` on. Narrow with `instanceof Error` or a `toError` helper rather than casting.
- Custom error classes should set `name`, accept `ErrorOptions` and pass them to `super`.
- Use `Error.cause` to add context when an error crosses a boundary, and keep the original stack.
- Reach for a Result type when a failure is an expected outcome the caller must handle.
- Rethrow anything you catch but do not understand.
