ThisCalculator

Everyday

TypeScript Error Model That Replaces Try Catch

Updated · Standard formula, shown below

The practical TypeScript error model that replaces most try/catch blocks is the Result type (also called Either), where functions return a discriminated union like Result<T, E> instead of throwing. You get back a value that is either { ok: true, value: T } or { ok: false, error: E }, and you handle both cases explicitly without exceptions unwinding through your call stack.

Why Throwing Errors Falls Short in TypeScript

JavaScript’s throw and try/catch come from a time when type safety didn’t exist. The compiler cannot track which functions throw, what they throw, or whether you caught everything. A function declared as fetchUser(id: string): Promise<User> might reject with a network error, a 404, a validation error, or a bug — none of which appear in the type signature. This makes errors invisible until runtime, forcing you to read implementation details or add defensive catches everywhere.

Even worse, try/catch catches everything in the block, including programming errors like TypeError: Cannot read properties of undefined. You end up catching bugs you didn’t intend to handle, and swallowing them silently. The Result type forces you to name the error type, making the failure modes part of the function’s contract.

The Result Type: A Minimal Implementation

A practical Result type is just a discriminated union. You don’t need a library — a few lines of TypeScript give you the core:

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

function ok<T, E>(value: T): Result<T, E> {
  return { ok: true, value };
}

function err<T, E>(error: E): Result<T, E> {
  return { ok: false, error };
}

Then a function that might fail returns Result<User, ApiError> instead of throwing. The caller must check the ok property before using value, and TypeScript narrows the type automatically:

const result = await getUser("123");
if (result.ok) {
  console.log(result.value.name); // User
} else {
  console.error(result.error.status); // ApiError
}

This is the entire model. The magic is that the compiler enforces the check — you cannot access value without first verifying ok is true, so missing error handling becomes a compile-time error instead of a runtime surprise.

How to Convert Throwing Functions to Result

Refactoring an existing codebase is straightforward. Start with the functions that are called most often, and wrap the body in a try/catch that returns err:

  1. Change the return type from Promise<T> to Promise<Result<T, E>>.
  2. Replace throw new Error(...) with return err(new Error(...)).
  3. Wrap the entire original body in try { ... return ok(value); } catch (e) { return err(e); }.
  4. At the call site, replace try { const x = await f(); } catch (e) { ... } with an if (result.ok) check.

For example, a typical database call goes from:

async function findUser(id: string): Promise<User> {
  const row = await db.query("SELECT * FROM users WHERE id = ?", [id]);
  if (!row) throw new NotFoundError("User not found");
  return row;
}

to:

async function findUser(id: string): Promise<Result<User, NotFoundError | DbError>> {
  try {
    const row = await db.query("SELECT * FROM users WHERE id = ?", [id]);
    if (!row) return err(new NotFoundError("User not found"));
    return ok(row);
  } catch (e) {
    return err(new DbError(e.message));
  }
}

Notice the error type is now explicit: NotFoundError | DbError. The caller knows exactly what can go wrong and can handle each case separately.

When to Keep Try/Catch (and When Not To)

Result types are not a universal replacement. There are two places where try/catch remains the right tool:

  • At the boundary of your application — where you finally catch all errors to log them, show a generic message, or crash. This is the “top level” of your app, like an Express error handler or a React error boundary.
  • For truly unexpected programming errors — bugs, assertion failures, or anything that should never happen. Result types are for expected failures (validation, network, not-found), not for bugs.

Inside your domain logic, however, Result types eliminate the need for most try/catch. You no longer need to wrap every call in a try block just to pass the error up. Instead, you propagate the Result value directly, and only the final boundary converts it to a thrown exception or an HTTP response.

Common Problems and How to Solve Them

The most frequent complaint is that checking result.ok everywhere is verbose. Solutions include:

  • Helper functions like unwrap() that throw if not ok (for cases where you truly cannot recover).
  • Pipelines using map and flatMap methods on the Result, so you chain operations without nested ifs.
  • TypeScript’s satisfies operator to ensure your error types are exhaustive.

Another issue is that the standard library and most npm packages throw. You have to wrap them at the call site, which is tedious. The pragmatic approach is to wrap only the functions you call frequently, and leave one-off calls in try/catch that immediately convert to a Result.

Finally, some developers worry about performance. In practice, creating a small object per result is negligible compared to the cost of a database query or network request. V8 engines optimize object allocation well, and the type safety gained far outweighs any microsecond overhead.

Comparison with Other Error Handling Approaches

TypeScript also offers neverthrow and fp-ts libraries that provide richer Result types with methods like map, andThen, and match. These are useful for large codebases but add a dependency and a learning curve. The minimal union type above gives you 80% of the benefit with zero dependencies.

Another alternative is the Either type from functional programming, which is identical in concept but uses Left and Right instead of ok/error. The Result naming is more intuitive for most TypeScript developers.

Some languages use checked exceptions (Java) or multiple return values (Go). TypeScript’s discriminated unions are closer to Go’s approach — explicit, but with better type narrowing. The key difference from Java is that checked exceptions are optional and often ignored, while Result types are enforced by the compiler.

Costs and Trade-offs

The main cost is verbosity. Every function that can fail must declare its error type, and every caller must handle it. This can feel like overhead for small scripts or prototypes. The benefit is that you never miss an error case, and the call stack is cleaner because you don’t have to trace through try/catch blocks.

Another cost is that Result types don’t integrate with async/await as smoothly as exceptions. You can’t use throw inside a Result-returning function; you have to return err. This makes control flow slightly more explicit but less natural for some developers.

There is also a learning curve for teams used to exceptions. They may initially write if (!result.ok) throw result.error everywhere, which defeats the purpose. Training and code review are necessary to enforce the pattern consistently.

Frequently Asked Questions

Does this work with async/await?

Yes, perfectly. Just return Promise<Result<T, E>> and use await normally. The result is a plain object, so you can await the promise and then check ok. There is no special handling needed.

What about errors that are truly unexpected, like a bug?

Let those throw. Result types are for expected failures that you want to handle gracefully. For programming errors, throwing is appropriate because you want the app to crash loudly and log the stack trace. You can still catch them at the boundary.

How do I handle multiple error types cleanly?

Define a union type for the error, like type ApiError = NetworkError | NotFoundError | ValidationError. Then your function returns Result<T, ApiError>. In the caller, you can use a switch on result.error.kind to handle each case.

Is this the same as Rust’s Result or Haskell’s Either?

Conceptually yes, but TypeScript’s implementation is simpler. Rust has built-in syntax like ? to propagate errors, which TypeScript lacks. You have to write the propagation manually or use helper functions like andThen.

Should I use a library like neverthrow or write my own?

For most projects, writing your own 10-line Result type is enough. Libraries add methods like map, flatMap, and match that reduce boilerplate, but they also add a dependency. Start with your own and add a library only if you find yourself repeating patterns.

Does this replace all try/catch blocks?

No, only most. You still need try/catch at the application boundary and for unexpected bugs. But inside your business logic, you can eliminate nearly all of them, making your code more predictable and your types more honest.

Related

Method: the standard formula for this calculation, rounded as each result states. See how the calculators work or report an error.