Skip to content
Velloreth
Programming 8 min read

Error Handling Patterns That Actually Work

Good error handling is a design decision, not a try/catch afterthought. Learn patterns for propagating, wrapping, and recovering from failures.

By

Errors are part of your API

The first thing to internalise is that error behaviour is part of a function’s contract. Callers need to know what can fail and how they will find out.

A function that can throw, return null, return an error object, or silently do nothing has four different contracts. Deciding which one applies is a design decision, and leaving it undecided is how inconsistent codebases happen.

Two kinds of errors

The most useful distinction is between programmer errors and operational errors.

Programmer errors are bugs. A null dereference, an out-of-bounds index, a violated invariant, a wrong type. These should not be handled — they should be fixed. The right response is to fail fast and loudly, so the bug is found in development rather than production.

Operational errors are expected failures in a running system. A network timeout, a file that does not exist, a database that is down, invalid user input. These should be handled, because they will happen and the system must cope.

The distinction determines the mechanism:

Programmer errorOperational error
Exampleundefined.fooNetwork timeout
Should happenNeverRegularly
ResponseCrash, fail fastHandle, retry, degrade
MechanismExceptionReturn value or exception

Mixing them up produces two failure modes: catching bugs and continuing with corrupt state, or crashing on a routine network blip.

Fail fast

Fail fast means detecting a problem as early as possible and stopping immediately.

function processOrder(order) {
  if (!order) throw new Error('order is required');
  if (!order.items?.length) throw new Error('order must have items');
  if (order.total < 0) throw new Error('order total cannot be negative');
  // now proceed with confidence
}

The alternative — checking later, or not at all — means the invalid state propagates and the failure surfaces somewhere unrelated, with a stack trace that points at the symptom rather than the cause.

Validation at the boundary is the practical form of this. Check inputs when they enter your system, then trust them internally.

Never swallow errors

The single worst error-handling pattern:

try {
  doSomething();
} catch (e) {
  // nothing
}

This turns a loud failure into a silent one. The operation did not happen, nothing was reported, and the symptom appears later in a place with no connection to the cause.

If you catch an error, you must do one of three things:

  1. Handle it — recover, retry, or substitute a default.
  2. Log it with context — record what failed and why.
  3. Rethrow it — propagate to a layer that can do one of the above.

An empty catch does none of these. It is almost always a bug.

The same applies to logging and rethrowing at every layer, which produces the same error five times in the logs and makes the real failure hard to find. Log once, at the boundary where you handle it.

Wrapping errors with context

As an error crosses a boundary, add context about what was being attempted.

async function loadUserProfile(userId) {
  try {
    return await db.query('SELECT * FROM users WHERE id = $1', [userId]);
  } catch (error) {
    throw new Error(`Failed to load profile for user ${userId}`, { cause: error });
  }
}

The cause option preserves the original error, so the stack trace shows both the original failure and the context added at each layer.

async function renderProfilePage(userId) {
  try {
    const profile = await loadUserProfile(userId);
    return render(profile);
  } catch (error) {
    throw new Error(`Failed to render profile page for user ${userId}`, { cause: error });
  }
}

The final error message reads: “Failed to render profile page for user 42” caused by “Failed to load profile for user 42” caused by the original database error. That chain is what makes production debugging possible.

Without wrapping, you get a raw database error with no indication of which user or which operation triggered it.

Custom error types

Distinguishing error kinds lets callers handle them selectively.

class AppError extends Error {
  constructor(message, options = {}) {
    super(message, options);
    this.name = this.constructor.name;
    this.statusCode = options.statusCode ?? 500;
    this.isOperational = options.isOperational ?? true;
  }
}

class ValidationError extends AppError {
  constructor(message, fields) {
    super(message, { statusCode: 400 });
    this.fields = fields;
  }
}

class NotFoundError extends AppError {
  constructor(resource) {
    super(`${resource} not found`, { statusCode: 404 });
  }
}

Now callers can branch on the type:

try {
  await updateUser(id, data);
} catch (error) {
  if (error instanceof ValidationError) return res.status(400).json({ fields: error.fields });
  if (error instanceof NotFoundError) return res.status(404).json({ error: error.message });
  throw error; // unknown — let the global handler deal with it
}

The isOperational flag is the key detail. It marks errors that are expected and safe to report to users, distinguishing them from bugs that should be logged and hidden behind a generic message.

Result types

Some languages and codebases prefer returning errors rather than throwing them.

function parseConfig(text) {
  try {
    return { ok: true, value: JSON.parse(text) };
  } catch (error) {
    return { ok: false, error };
  }
}

const result = parseConfig(input);
if (!result.ok) {
  console.error('Invalid config:', result.error.message);
} else {
  use(result.value);
}

The advantage is that the failure is visible in the type signature — the caller cannot forget it exists. The disadvantage is verbosity, and the fact that it does not compose well with exceptions from libraries.

Rust and Go use this style natively. In JavaScript and Python, exceptions are idiomatic, and result types are usually reserved for expected failures like validation.

Retry with backoff

Transient failures — network blips, rate limits, temporary unavailability — often succeed on retry.

async function retry(fn, { attempts = 3, baseDelay = 100 } = {}) {
  for (let i = 0; i < attempts; i++) {
    try {
      return await fn();
    } catch (error) {
      if (i === attempts - 1) throw error;
      if (!isRetryable(error)) throw error;
      const delay = baseDelay * 2 ** i + Math.random() * 100; // jitter
      await new Promise((r) => setTimeout(r, delay));
    }
  }
}

Three details matter:

  • Only retry retryable errors. A 400 Bad Request will fail again; a 503 might not.
  • Use exponential backoff. Doubling the delay avoids hammering a struggling service.
  • Add jitter. Random variation prevents all clients retrying at the same instant, which is the thundering herd problem.

Circuit breakers

When a dependency is failing consistently, retrying makes things worse. A circuit breaker stops calling it for a while.

The states are:

  • Closed — calls pass through normally.
  • Open — calls fail immediately without attempting.
  • Half-open — a few trial calls are allowed to test recovery.
class CircuitBreaker {
  #failures = 0;
  #state = 'closed';
  #openedAt = 0;

  async call(fn) {
    if (this.#state === 'open') {
      if (Date.now() - this.#openedAt < 30_000) throw new Error('Circuit open');
      this.#state = 'half-open';
    }
    try {
      const result = await fn();
      this.#failures = 0;
      this.#state = 'closed';
      return result;
    } catch (error) {
      this.#failures++;
      if (this.#failures >= 5) {
        this.#state = 'open';
        this.#openedAt = Date.now();
      }
      throw error;
    }
  }
}

This gives a failing dependency time to recover and prevents your service from exhausting its own resources waiting on it.

Graceful degradation

Not every failure needs to be fatal. Sometimes a partial result is better than none.

async function getDashboard(userId) {
  const [profile, stats, recommendations] = await Promise.allSettled([
    fetchProfile(userId),
    fetchStats(userId),
    fetchRecommendations(userId),
  ]);

  return {
    profile: profile.status === 'fulfilled' ? profile.value : null,
    stats: stats.status === 'fulfilled' ? stats.value : null,
    recommendations: recommendations.status === 'fulfilled' ? recommendations.value : [],
  };
}

The dashboard renders with whatever succeeded. A failure in recommendations does not blank the whole page.

A global handler

Every application needs a last line of defence.

process.on('uncaughtException', (error) => {
  logger.fatal({ error }, 'Uncaught exception');
  process.exit(1); // the process is in an unknown state
});

process.on('unhandledRejection', (reason) => {
  logger.fatal({ reason }, 'Unhandled rejection');
  process.exit(1);
});

The important detail is that after an uncaught exception, the process should exit. The state is unknown, and continuing risks corrupting data. Log, then die, and let the supervisor restart.

Practical guidance

  • Validate at the boundary, then trust internally.
  • Fail fast on programmer errors; handle operational errors.
  • Never swallow — handle, log, or rethrow.
  • Wrap with context as errors cross boundaries, using cause.
  • Log once, at the handling boundary, with structured context.
  • Distinguish operational from programmer errors with a flag or type.
  • Retry only retryable errors, with backoff and jitter.
  • Degrade gracefully where a partial result is useful.
  • Exit on uncaught exceptions rather than continuing in an unknown state.

For the testing angle, see why your tests are slow and debugging strategies that work. For the reliability context, incident response for solo developers and zero trust for small teams.

Quotable summary

Error behaviour is part of a function’s contract, so deciding how errors propagate is a design decision. Programmer errors are bugs and should fail fast; operational errors are expected and should be handled, and the two need different mechanisms. Never swallow an error silently — handle it, log it with context, or rethrow it. Wrap errors with context as they cross boundaries, preserving the original as a cause, so the final message explains what was being attempted. Use custom error types to let callers branch on kind, and an isOperational flag to distinguish expected failures from bugs. Retry only retryable errors with exponential backoff and jitter, use circuit breakers for consistently failing dependencies, and exit the process after an uncaught exception rather than continuing in an unknown state.

Frequently asked questions

What is the difference between an error and an exception?
An error is any condition that prevents normal completion. An exception is a language mechanism for signalling and propagating errors. Not all errors are exceptions — a returned error value is an error without an exception.
Should I use exceptions or return values for errors?
Use return values for expected, recoverable failures that callers must handle, such as a validation failure or a not-found result. Use exceptions for unexpected failures that should abort the current operation, such as a missing configuration or a broken invariant.
What does it mean to fail fast?
Fail fast means detecting a problem as early as possible and stopping immediately, rather than continuing with invalid state. It makes bugs easier to locate because the failure is close to its cause.
Why is swallowing errors bad?
Because it hides failures. An empty catch block turns a loud problem into a silent one, and the symptom appears far from the cause. If you catch an error, do something with it: handle it, log it with context, or rethrow it.
What is error wrapping?
Error wrapping means catching an error and rethrowing a new one that includes the original as a cause, plus context about what was being attempted. It preserves the original stack while adding information at each layer.
How should I log errors?
Log them once, at the boundary where they are handled, with structured context: what operation failed, the relevant identifiers, and the original error. Do not log and rethrow at every layer, which produces duplicate noise.