Skip to content
Clean CodeChapter 11 / 57Intermediate6 min read

Fail Fast, No Defensive Fallbacks

Fail fast vs defensive programming. Why a clear error beats hiding missing data with ?? [], and when ?? is fine. TypeScript examples.

On this page

1. What is this practice?

"Defensive" code adds defaults everywhere to stop crashes. It sounds good, but stopping a crash and stopping a bug are different things. Failing fast means surfacing a mistake early and loudly, right where it happened.

SituationRight approach
The value is truly optional (a user's nickname, a config option)value ?? default is perfectly fine
The value must exist (a database row, a required field)if (!value) and throw
There are two valid pathsA clear if / else, both on purpose

2. Why does it matter?

A fallback stops the crash, not the bug. The bug hides, keeps going, and shows up somewhere else in another form, where its cause is very hard to find.

Defensive fallbackFail fast
order.items ?? [] shows an empty order, but the customer already paidError: order 42 has no items, you know right away
The dashboard shows 0 revenue and everyone thinks there were no salesThe API bug is caught on day one
The bug is found weeks later through a support ticketThe bug is found in development or on the first deploy
Wrong data gets saved to the databaseThe work stops and no bad data is created
The error appears in one place, the cause is in anotherThe error appears exactly where the problem is

3. When to follow it

LevelHow importantWhy
Learning projectUnderstand when ?? hides thingsBeginners "fix" every error with ??, break that habit early
Production codeVery importantHidden bugs create bad data and wrong money
Senior levelTrace it back to the producerA senior fixes the cause, not the symptom

4. Bad vs good code

ts
async function invoiceTotal(invoiceId: string) {
  const invoice = await db.invoice.findUnique({ where: { id: invoiceId } });
  const lines = invoice?.lines ?? [];
  const rate = invoice?.customer?.taxRate ?? 0;

  try {
    return lines.reduce((sum, line) => sum + line.amount, 0) * (1 + rate);
  } catch {
    return 0;
  }
}
ts
async function invoiceTotal(invoiceId: string) {
  const invoice = await db.invoice.findUnique({
    where: { id: invoiceId },
    include: { lines: true, customer: true },
  });

  if (!invoice) {
    throw new NotFoundError(`Invoice ${invoiceId} not found`);
  }

  return subtotal(invoice.lines) * (1 + invoice.customer.taxRate);
}
What is the difference?BadGood
Invoice not foundTotal is 0, nobody knows whyA clear NotFoundError
Tax rate missingSilently 0, wrong billRequired in the schema, it cannot be missing
Empty catchSwallows every errorThe error goes up and gets logged
DebuggingHours of "why is the total 0?"The error message has the id and the reason

Why not ?? throw

Some people write a helper to throw in one line:

ts
const user = (await users.find(id)) ?? fail("User missing");

The strict house style asks for an explicit check instead, so every throw is visible at a glance and the guard pattern looks the same everywhere:

ts
const user = await users.find(id);

if (!user) {
  throw new NotFoundError(`User ${id} not found`);
}

Pass the error up with context

ts
try {
  await payments.charge(order);
} catch (error) {
  throw new Error(`Charging order ${order.id} failed`, { cause: error });
}

cause keeps the original error attached, and the message says which task failed.

5. How to apply it

Before writing a fallback
Is this value optional by contract?
Yes: ?? default is fine
No: it being missing is a bug
Add a guard and throw with a clear message
Find out where the value is produced
Fix the bug there, do not patch the symptom

On the frontend, a backend mistake is often hidden with ?? []. The real fix is in the backend: it should always send that field, or the contract should mark it optional and the UI should show a clear empty state.

6. Exceptions and common mistakes

The whole app should not crash in front of the user. Failing fast does not mean a white screen. Catch the error at a boundary (a React error boundary, the API error handler), log it, and show the user a clear message. Just do not swallow it quietly in the middle and invent a fake value.

For things like network calls, retries and a graceful fallback (showing cached data) are a deliberate design, not a hidden bug. The difference is that they are intentional and logged.

Mistake: ?? [] or ?? {} on required data

Why? Instead of a crash you get a wrong UI or wrong numbers, and the bug is found late.

Better: Guard and throw, then fix the bug in the producer.

Mistake: An empty catch block

Why? Every error, from a network failure to a typo, disappears silently.

Better: Log the error with context, or rethrow it with a cause.

Mistake: Optional chaining chains everywhere

Why? a?.b?.c?.d shows that you do not know the shape of the data, and undefined quietly travels onward.

Better: Parse the data at the boundary, then trust the types.

Mistake: No context in the error message

Why? Something went wrong does not tell you which record, which user or which task.

Better: Put the id and the task name in the message, and attach the cause.

7. What to learn before and after

Final quick revision

CheckQuestion
Optional?Is ?? used only on a truly optional value?
RequiredDoes a missing required value throw?
CatchIs there any empty catch?
ContextDoes the error message have the id and the task?
Root causeWas the bug fixed at the producer?
BoundaryDoes the user get a clear message instead of a crash?