Contents Lesson 9 of 18

13 min read · foundations

When the data does not arrive

By the end of this lesson you will have a failure screen that says which failure it is — a rejected key, a spent day or a busy minute — and tests that prove each branch without sending a single request.

Everything so far assumed the response comes back and is correct. Most of the time it does. The rest of the time is what decides whether you trust your own tool at 7am.

Four ways a market tool fails, and they are not the same

Generated code usually has one failure branch, if any. There are four, and they need different answers.

No key. The environment variable is missing: a fresh clone, or a deploy where you forgot to set it. The tool cannot work at all, and the fix is a specific action you can name. Say exactly that: copy .env.example, add the key, restart. Never a blank page.

A rejected key. The key exists but the API said no: revoked, or a plan that does not cover the instrument you asked for. Same visible symptom, completely different fix. Distinguishing them saves an hour of looking in the wrong place.

Out of quota. You have spent the day's allowance. Your tool is fine and will work again tomorrow, but the current screen has no data, and the honest thing is to say why, with the meter beside it. This is not an error in your code, and dressing it up as one teaches you to distrust working software. The API says it with 402, and the allowance resets at midnight GMT, so retrying sooner only fails again. Do not confuse it with 429: that is a different limit — too many requests within one minute — which clears by itself, and its Retry-After header says when. The starter's proxy already tells the two apart; your screen should too.

A bad ticker. One symbol in the list does not exist or is not covered. The list is not broken; one row is. Fail that row, keep the others.

That last one is the design principle for the whole screen: partial data is not failure. Eleven rows and one hole is a working tool. Eleven rows thrown away because of one hole is a tool that will annoy you into rewriting it.

Check the response before you parse it

The single most common omission in generated fetch code:

const res = await fetch(url);
if (!res.ok) {
  return { error: `EODHD ${res.status}` };   // 402, 403, 429, 404 all land here
}
const body = await res.json();

Without the res.ok check, res.json() happily parses an error body into your table and you render blanks. The status code is the difference between "your plan does not cover this" and "you are out of calls", and it is free information you threw away.

Timeouts, because a hung request is worse than a failed one

A request that never returns leaves your page spinning forever. Give every outbound call a deadline:

const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), 15_000);
try {
  return await fetch(url, { signal: controller.signal });
} finally {
  clearTimeout(timer);
}

The finally is not decoration: without it a fast response leaves a timer running, and enough of those is a leak.

"NA" is a value, not an error

Market APIs return placeholder strings where a number is unavailable: a field that has never been reported, a market that has not opened. Your code asks for a number and gets "NA", which is not null, not an error status, and will happily flow into your formatting function and render as NaN.

Validate the shape at the boundary, once, rather than defending in every component:

function isQuote(row: any): boolean {
  return typeof row.code === "string"
    && typeof row.close === "number"
    && typeof row.change === "number";
}

Rows that fail get dropped or marked; rows that pass are trustworthy everywhere downstream. One check at the edge beats twenty defensive checks in the UI.

Empty states teach; blank pages do not

Three screens deserve real writing, and all three are places a person is confused:

  • Empty list names the file to edit: "Your watchlist is empty. Add tickers in src/lib/watchlist.ts."
  • Loading is a skeleton in the shape of the table, so nothing jumps when data lands.
  • Failed gives the specific cause and the specific next step, from the four above.

Write these before you need them. You will need them on the morning you are in a hurry, which is precisely when a blank page costs the most.

Try it now

The prompt

Mock mode on. Start the agent, press Shift+Tab until plan mode is on, and paste:

Today quotes() in src/lib/quotes.ts returns null for every failed
answer, so the page cannot tell a rejected key from a spent day. Make
the failure screen say which failure it is and what to do: 401, the key
was not accepted (check it, restart); 402, today's calls are spent (the
count resets at midnight GMT); 429, too many requests this minute (wait,
then reload); anything else, the status code. Plan first and name the
files. Write the tests in tests/failures.test.ts before any code,
stubbing fetch the way tests/proxy.test.ts does, and show me them
failing. No real request: the tests stub the network. Then make them
pass. If changing what quotes() returns breaks an existing test, update
that test too and tell me which one. Run npm test, npm run typecheck
and npm run check:leak.

Approve the plan only if it names the files and puts the tests first. A good answer changes src/lib/quotes.ts and src/app/page.tsx, adds tests/failures.test.ts, probably adjusts one line of an existing test that used the old return value, and shows you red before green. If the code the tests import does not exist yet, the red run may be the whole test file failing to load (Cannot find package and a file name) rather than one red line per test. That counts as red; the next lesson explains why, and asking for an empty stub of the new code first gets you one red line per test instead.

Check it yourself

  1. The plan named the files before any edit, and the first npm test run showed the new tests failing.
  2. The second run is green, with the starter's own tests still passing beside the new ones.
  3. git status shows the two source files, the new test file and at most the existing test you were told about, nothing else (no .env* file).
  4. npm run check:leak passes: the new messages carry a status and a sentence, never the key.

Break it on purpose

Produce the failures on purpose and look at what your tool shows, with mock mode off; each load costs its calls like any other, the nonsense ticker included. Remove the key from .env.local and restart (the page shows its own "No key found" message without sending any request, so no status from the table below applies). Put a nonsense ticker like NOTREAL.US in the list. Corrupt the key by one character. Quota you cannot exhaust on demand, so that branch waits for a real morning, and until then the test is what covers it. For each one, ask: does the screen tell me which failure this is, and what to do next? Fix the ones that do not.

This is what the API sends back to the tool's multi-symbol quote request in each case with a key of your own, measured on 28 September 2026. (With the demo token, any ticker it does not cover, NOTREAL.US included, makes the whole request answer 403 and the page shows no table: that is the demo token refusing before it looks anything up, not the row of "NA" below. Use a key of your own for this step, or read the table instead of reproducing the last row.)

What you did Status Content-Type Body
Removed the key (no api_token at all) 401 text/html Unauthenticated
Left api_token=undefined, what a template string makes of a missing variable 401 text/html Unauthenticated
Corrupted the key by one character 401 text/html Unauthenticated
Added NOTREAL.US to the list 200 application/json the other rows as normal, plus a NOTREAL.US row whose prices, volume and change fields are all "NA"

Two things follow. The API cannot tell a missing key from a wrong one, so your tool has to: check that the variable exists before it sends anything. And the bad ticker is not an error status at all; it arrives as a row of "NA", which is exactly what the shape check at the boundary is for.

You just ran four checks by hand. The status codes are tests now; the next lesson turns the bad ticker and the missing key into tests as well, so you never have to remember them again.

Compare with ours

The lines that decide it
// src/lib/quotes.ts: a failure keeps its status instead of becoming null
if (!res.ok) return { failed: res.status };

// src/app/page.tsx: one sentence per status, each with the next step
const WHY: Record<number, string> = {
  401: "The API did not accept the key. Check EODHD_API_KEY in .env.local, then restart.",
  402: "Today's API calls are spent. The count resets at midnight GMT.",
  429: "Too many requests in one minute. Wait a minute, then reload.",
};

One test per status, each with fetch stubbed to answer that code. The starter's branch ref/build-your-first-tool/u2 carries this unit's changes.

Checkpoint

git status   # only the files you expect, and no .env*
git add -A
git commit -m "Name the failure: a rejected key, a spent day and a busy minute need different fixes"

Then answer this lesson's questions.