In Watch Four Countries Load Together, Mateo’s row failed twice. The second failure raised TypeError: Cannot read properties of undefined (reading '0'), which came from the last line of your own getCountry(), after the World Bank had answered 200. The other three friends were fine, but that message says nothing about Mateo’s typo.
In this lesson, you’ll check each response’s body at the point where it enters the planner. You’ll make getCountry() and getHolidays() return plain data the rest of the program can trust or throw an error that says clearly which country has no data. Start with the body that got past the ok check.
Read What the ok Check Let Through
The ok check tells you that the status is a success, from 200 to 299, not that the body holds what you asked for. To see what the World Bank sent for Mateo’s code, ask for it with curl -i. Most of the headers are left out here, and the body is wrapped for display:
$ curl -i "https://api.worldbank.org/v2/country/XX?format=json"
HTTP/2 200
content-type: application/json;charset=utf-8
...
[{"message":[{"id":"120","key":"Invalid value",
"value":"The provided parameter value is not valid"}]}]
Without --http1.1, curl spoke HTTP/2, which prints no phrase after the code and writes header names in lowercase. The status line says 200, and the Content-Type says JSON, so everything before the body looks like success. Only the body says the request failed. This output is from a run on November 27, 2026.
Compare the body with Portugal’s, which is an array of two elements, the paging details at index 0 and a list with one country at index 1. Mateo’s is an array of one element, an object holding a message list. There’s no index 1, so data[1] is undefined, and data[1][0] throws.
Watch out: an API’s docs show one example response, but real responses can leave fields out, contain an empty list or null, and change over time. A nested read such as data[1][0] that follows the example works only while every response matches that example.
The fix is to check the shape at the boundary, the place where data from outside becomes your program’s data. For getCountry(), that’s right after response.json(). If the function checks the body there, then every caller gets either a country it can use or an error that says why there isn’t one.
Before you write the check, decide what the planner should say when something is missing. Without a country’s name, the planner has nothing to show for that friend, so a missing name is an error. A missing capital city is different. The planner can still list the country, so it’s better to return null for the capital city and let the caller print something sensible.
Check the Country Record at the Boundary
getCountry() has to decide, from the body alone, whether it got a country. Put that decision in a function of its own, so you can test it with bodies you type in. Save this as country_check.mjs in your planner folder: