Error Handling in TypeScript: Result Types vs Exceptions

After five years of maintaining a 300k-line TypeScript codebase that powers payment processing and ledger reconciliation, I can tell you that how you handle errors matters more than how you model your happy path. For a long time, my team relied exclusively on try/catch and thrown exceptions. It felt idiomatic, it matched JavaScript, and it was invisible — until it wasn't. We started seeing production incidents where a forgotten catch bubbled an unhandled rejection through three service layers, or a refactor silently changed which function could throw. When we migrated our core domain logic to Result types, our incident rate for unhandled errors dropped by over 60% and, more importantly, the compiler started catching the mistakes we used to catch in code review. This article is a practical comparison of those two approaches: not a theoretical debate about monads, but a guide to what actually works in production TypeScript.

Why TypeScript's Try/Catch Turns Error Paths Into Invisible Contracts

The fundamental problem with exceptions in TypeScript is that they are not part of the type signature. When you look at a function like function parseInvoice(input: string): Invoice, there is no indication that it might throw a SyntaxError, a ValidationError, or a network timeout. You have to read the implementation, or the documentation if it exists, to know. The MDN Web Docs on try...catch correctly describes the runtime semantics, but TypeScript's type checker does not track which functions throw or what they throw. That information is erased.

In my experience, this invisibility creates three concrete problems at scale. First, refactoring becomes unsafe. If I extract a helper that now calls a throwing parser, no call site is forced to update. Second, error handling becomes all-or-nothing. Developers wrap large blocks in a single try/catch because they cannot remember every throw site, which conflates distinct failure modes. Third, typed errors are impossible. A catch (e: unknown) gives you unknown — which is correct — but forces you to do runtime narrowing for every catch block, and most teams simply cast to Error and hope.

The Lie of Exhaustive Catch Blocks

I've found that teams try to compensate by creating custom error hierarchies: class NotFoundError extends Error, class ConflictError extends Error, and then they write catch blocks that check instanceof. This works until you cross an async boundary or a serialization layer where the prototype chain is lost. More critically, TypeScript will never warn you if you forgot to handle ConflictError. You can write an exhaustive if/else if chain in a catch block, but the compiler cannot verify its completeness the way it can with a discriminated union.

// The signature hides the failure modes
async function chargePayment(paymentId: string): Promise<Receipt> {
  const payment = await db.payments.findOrThrow(paymentId); // throws NotFoundError?
  if (payment.status !== 'authorized') {
    throw new InvalidStateError(`Cannot charge ${payment.status}`); // undocumented throw
  }
  return gateway.capture(payment); // throws GatewayError, TimeoutError?
}

// Caller has no compiler help
try {
  const receipt = await chargePayment(id);
  return receipt;
} catch (e) {
  // Is e a NotFoundError? InvalidStateError? TypeError from a bug?
  // We have to guess and narrow at runtime.
  logger.error(e as Error);
  throw e;
}

That pattern is serviceable for scripts, but for domain logic where failure is expected — validation, insufficient funds, external service degradation — invisible error contracts make the system brittle.

Modeling Fallible Operations with Discriminated Union Result Types

A Result type makes the failure explicit in the return type. Instead of throwing, a function returns a value that represents either success or failure. This is not a new idea; it is the Either monad from functional programming, but in TypeScript it is most naturally expressed as a discriminated union. The pattern is simple and does not require a library, though libraries like neverthrow or ts-results add useful helpers.

In our codebase we define a minimal Result as follows, and we reuse it everywhere. If you are unfamiliar with discriminated unions, they are the foundation for this pattern, as I detailed in Discriminated Unions in TypeScript: Modeling Domain Logic Safely.

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

type PaymentError = 
  | { kind: 'not_found'; paymentId: string }
  | { kind: 'invalid_state'; currentStatus: string }
  | { kind: 'gateway_declined'; code: string };

function parseAmount(raw: string): Result<number, { kind: 'invalid_amount' }> {
  const n = Number(raw);
  if (!Number.isFinite(n) || n <= 0) {
    return { ok: false, error: { kind: 'invalid_amount' } };
  }
  return { ok: true, value: n };
}

async function chargePayment(paymentId: string): Promise<Result<Receipt, PaymentError>> {
  const payment = await db.payments.find(paymentId);
  if (!payment) {
    return { ok: false, error: { kind: 'not_found', paymentId } };
  }
  if (payment.status !== 'authorized') {
    return { ok: false, error: { kind: 'invalid_state', currentStatus: payment.status } };
  }
  const res = await gateway.capture(payment);
  if (!res.ok) {
    return { ok: false, error: { kind: 'gateway_declined', code: res.code } };
  }
  return { ok: true, value: res.receipt };
}

Now the caller cannot ignore the error. TypeScript forces a check on result.ok before you can access result.value. If you add a new variant to PaymentError, every switch (result.error.kind) that is not exhaustive will produce a compiler error when you enable strict and use a never check. That is the guarantee we were missing with exceptions.

Composing ResultsWithout Nested Conditionals

The common complaint about Result types is verbosity: endless if (!result.ok) return result blocks. I've found that complaint disappears once you add two small combinators. For a deeper look at the generic patterns that make these helpers type-safe, see TypeScript Generics: Practical Examples Beyond the Basics.

function map<T, U, E>(result: Result<T, E>, fn: (v: T) => U): Result<U, E> {
  return result.ok ? { ok: true, value: fn(result.value) } : result;
}

function flatMap<T, U, E>(result: Result<T, E>, fn: (v: T) => Result<U, E>): Result<U, E> {
  return result.ok ? fn(result.value) : result;
}

function andThen<T, U, E>(result: Result<T, E>, fn: (v: T) => Result<U, E>): Result<U, E> {
  return flatMap(result, fn);
}

// Usage: chain validations without nesting
const result = andThen(parseAmount(input), (amount) =>
  andThen(validateCurrency(currency), (cur) =>
    createPaymentIntent(amount, cur)
  )
);

if (!result.ok) {
  // result.error is fully typed
  switch (result.error.kind) {
    case 'invalid_amount': return res.status(400).send('Invalid amount');
    case 'unsupported_currency': return res.status(400).send('Currency not supported');
    default: {
      const _exhaustive: never = result.error;
      throw new Error(`Unhandled error: ${_exhaustive}`);
    }
  }
}

We also defined mapErr and unwrapOr helpers, but map and flatMap handle 90% of cases and keep business logic linear.

Wiring Result Types Through Async Boundaries and Promise Chains

The real test for any error strategy is how it behaves across async/await and Promise combinators. Exceptions have a clear story here: an exception thrown in an async function rejects the promise, which you catch with try/catch or .catch(). Results require more thought because Promise<Result<T,E>> is not the same as Result<Promise<T>,E>.

I've settled on a strict rule: domain functions always return Promise<Result<T,E>> and never throw for expected failures. Infrastructure functions — database drivers, fetch — will still throw, so we catch at the boundary and convert. This keeps the promise rejection channel reserved for truly exceptional bugs: out-of-memory, programmer errors, and cancelled requests.

Converting Throwing APIs at the Edge

Do not let throwing APIs leak into your domain. Wrap them once, at the adapter layer, and convert the exception into a typed error. This also solves the problem of integrating with runtime validation. For example, when parsing external JSON we use Zod to produce a typed Result instead of throwing on invalid data, a pattern I described in Runtime Type Validation with Zod: Bridging TypeScript and External Data.

async function safeFetch<T>(
  url: string,
  schema: z.ZodSchema<T>
): Promise<Result<T, { kind: 'network_error'; cause: unknown } | { kind: 'parse_error'; issues: string }>> {
  try {
    const res = await fetch(url);
    if (!res.ok) {
      return { ok: false, error: { kind: 'network_error', cause: `HTTP ${res.status}` } };
    }
    const json = await res.json();
    const parsed = schema.safeParse(json);
    if (!parsed.success) {
      return { ok: false, error: { kind: 'parse_error', issues: parsed.error.message } };
    }
    return { ok: true, value: parsed.data };
  } catch (e) {
    // Only transport/network failures end up here
    return { ok: false, error: { kind: 'network_error', cause: e } };
  }
}

// Parallel composition stays typed
async function loadDashboard(userId: string) {
  const [userRes, billingRes] = await Promise.all([
    safeFetch(`/users/${userId}`, UserSchema),
    safeFetch(`/billing/${userId}`, BillingSchema),
  ]);

  if (!userRes.ok) return userRes;
  if (!billingRes.ok) return billingRes;

  return { ok: true, value: { user: userRes.value, billing: billingRes.value } } as const;
}

Notice that Promise.all still works — it resolves to an array of Results, not a rejected promise. You retain full control over partial failures. With exceptions, Promise.all fails fast on the first rejection, which is often not what you want for a dashboard that can render partial data. If you do want fail-fast with Results, implement a sequence helper that short-circuits.

The Hidden Cost of Exception-Based Control Flow in Large Codebases

Performance is a secondary concern, but maintainability cost is not. In V8, throwing is optimized for the non-throwing path: the happy path is fast, but the throw path is expensive because it captures a stack trace. That trade-off is fine when exceptions are rare. When validation failures or expected business errors use exceptions as control flow, you pay that cost frequently. I profiled a CSV import that validated 100k rows by throwing ValidationError per row; switching to Result reduced the import time by 38% simply by avoiding stack trace allocation.

The larger cost is cognitive. Exceptions create non-local control flow. Consider this real example from our legacy order processing pipeline:

async function processOrder(orderId: string) {
  try {
    const order = await getOrder(orderId);
    await reserveInventory(order);
    await chargePayment(order.paymentId);
    await sendConfirmation(order);
  } catch (e) {
    if (e instanceof InventoryError) {
      await compensateInventory(orderId);
    }
    // Did chargePayment throw? Did reserveInventory?
    // We don't know without reading each implementation.
    await markFailed(orderId, e as Error);
  }
}

Every new developer on the team asked the same question: which lines can actually fail and how? With Results, the answer is in the signature:

async function processOrder(orderId: string): Promise<Result<void, OrderError>> {
  const orderRes = await getOrder(orderId);
  if (!orderRes.ok) return orderRes;

  const reserveRes = await reserveInventory(orderRes.value);
  if (!reserveRes.ok) return reserveRes;

  const chargeRes = await chargePayment(orderRes.value.paymentId);
  if (!chargeRes.ok) {
    await compensateInventory(orderId);
    return chargeRes;
  }

  return sendConfirmation(orderRes.value);
}

Yes, it is more lines. But every error path is explicit, reviewable, and testable. You can unit test processOrder by mocking each step to return a specific Result variant, without relying on jest.spyOn().mockRejectedValue(). In my experience, tests for Result-based code are shorter and less flaky because they don't need to assert on thrown error instances or async rejection matchers.

Interoperating Between Result Types and Legacy Throwing APIs

You will never convert an entire codebase at once. The pragmatic strategy is to establish a core domain where Results are mandatory and an outer shell where exceptions are tolerated, with a clear translation layer between them. For our Express API, we use a single top-level error boundary that converts Results to HTTP responses and catches truly unexpected throws.

The Boundary Wrapper Pattern I Use in Production

We wrap every route handler with a function that handles both semantics. Domain services return Results; controllers translate them. Infrastructure that throws is wrapped with a tryResult helper.

function tryResult<T, E>(fn: () => T, onError: (e: unknown) => E): Result<T, E> {
  try {
    return { ok: true, value: fn() };
  } catch (e) {
    return { ok: false, error: onError(e) };
  }
}

async function tryResultAsync<T, E>(fn: () => Promise<T>, onError: (e: unknown) => E): Promise<Result<T, E>> {
  try {
    const value = await fn();
    return { ok: true, value };
  } catch (e) {
    return { ok: false, error: onError(e) };
  }
}

// Express boundary
function handler<T>(
  fn: (req: Request) => Promise<Result<T, ApiError>>
) {
  return async (req: Request, res: Response, next: NextFunction) => {
    try {
      const result = await fn(req);
      if (!result.ok) {
        const status = errorToStatusCode(result.error);
        res.status(status).json({ error: result.error });
        return;
      }
      res.json(result.value);
    } catch (e) {
      // Only for programmer bugs, not domain errors
      next(e);
    }
  };
}

app.post('/payments/:id/charge', handler(async (req) => {
  // chargePayment never throws for domain errors
  return chargePayment(req.params.id);
}));

This pattern also makes incremental migration tractable. We started by migrating pure validation and payment logic, then moved outward to repositories. Files that still throw are marked with a comment // THROWS: legacy so reviewers know to wrap them. Over six months we converted about 70% of the domain without a feature freeze. New code defaults to Result; legacy code is wrapped at the call site.

One nuance: never throw a Result, and never return an Error from a Result. Keep the channels separate. If you find yourself writing throw result.error, you have collapsed the abstraction and lost the benefit.

Choosing Your Error Strategy: When Results Outweigh Throws

There is no universal winner. I use a simple heuristic that has held up across three teams: if the caller is expected to recover, return a Result; if the caller cannot plausibly recover, throw. Validation errors, business rule violations, missing entities, and external service degradations are all recoverable — the caller can show a message, retry, or choose an alternative path. Out-of-memory, assertion failures, and programmer errors are not recoverable — crashing and reporting is correct. The IETF RFC Standards for HTTP, for example, distinguish 4xx client errors from 5xx server failures for similar reasons; your error types should reflect that same distinction.

Criterion Result Type (Discriminated Union) Thrown Exception
Type Safety Compiler enforces handling; exhaustive checks on error variants Invisible in signature; catch receives unknown, no exhaustiveness
Composability Chains with map / flatMap; works cleanly with Promise.all Non-local control flow; breaks composition across async boundaries
Performance (expected failures) No stack trace allocation; fast for high-frequency validation Stack trace captured on throw; significant overhead if frequent
Debuggability Requires explicit context in error value; no automatic stack Automatic stack trace; superior for unexpected crashes
Interoperability Requires wrapping of throwing libs; explicit conversion at edge Native to JavaScript; zero friction with existing APIs
When to Use Domain logic, validation, recoverable business errors Programmer bugs, assertion failures, truly exceptional states

If you are starting a new TypeScript project, I recommend defaulting to Results for all domain operations and reserving throws for invariant violations. Introduce a shared Result utility early and agree on an error taxonomy — a flat union per bounded context works better than a deep class hierarchy. If you are maintaining a legacy codebase, do not attempt a big-bang rewrite. Instead, enforce Results in new modules, wrap old throwers at the boundary, and let the type checker gradually pull the rest of the system toward explicit errors. The payoff is not just fewer incidents; it is code where the failure modes are as readable as the success path.

Frequently Asked Questions

Should I use a library for Result types or write my own?

For most teams, a 15-line discriminated union type you own is preferable to a dependency. Libraries like neverthrow add useful methods such as match, orElse, and asyncAndThen that reduce boilerplate, but they also introduce their own conventions and bundle size. I've found that starting with your own minimal Result and adding helpers like map and flatMap as needed keeps the abstraction transparent. Adopt a library only if you need interoperability with a large ecosystem that already uses it.

How do Result types work with TypeScript's strict null checks?

They complement each other. A Result makes the error case explicit, while strict null checks prevent accidental access to value before confirming ok === true. When you check if (!result.ok) return result, TypeScript narrows the remaining branch to { ok: true; value: T }, so result.value is safe. This is far safer than returning T | null and relying on null checks, because the error carries typed context about why it failed instead of just absence.

Do Result types eliminate the need for try/catch entirely?

No. You still need try/catch at the edges where you interact with code that throws — JSON.parse, Node's fs, third-party SDKs, and any Promise that may reject for network reasons. The pattern is to catch at the boundary and immediately convert the caught exception into a typed Result variant. Inside your domain layer, however, you can avoid try/catch completely and use exhaustive switches on the error union instead.

Will using Result types make my code significantly more verbose?

Initially, yes — you will write more explicit if (!result.ok) guards than you did with a single encompassing try/catch. In my experience that verbosity stabilizes after you add two combinators (map and flatMap) and a small set of error-to-HTTP mappers at the controller layer. The net line count for a feature often stays flat, because you remove defensive instanceof chains and hidden retry logic. More importantly, the lines you add are directly tied to business requirements and are verified by the compiler.

Related Articles

References & Standards: Python Documentation · MDN Web Docs · IETF RFC Standards