Status codes and error handling — what AI's API calls do when the wire blinks — step 9 of 9
One last thing before we move on. Same surface as a write step — but the lesson doesn't complete until this passes.
Last drill. Write a function safe_fetch(response) that takes a
fake response dict (with status and body keys) and returns:
- The dict's
bodyif the status is 2xx (success). - The string
"not found"for status 404 specifically. - The string
"client error"for any other 4xx. - The string
"retry later"for any 5xx. - Raise
ValueError(f"unexpected status: {status}")for anything else (1xx, 3xx).
The starter has four responses to pass through. Use the bottom loop as-is.
Expected output:
{'id': 7}
not found
client error
retry later
One last thing before we move on. Same surface as a write step — but the lesson doesn't complete until this passes.
Last drill. Write a function safe_fetch(response) that takes a
fake response dict (with status and body keys) and returns:
- The dict's
bodyif the status is 2xx (success). - The string
"not found"for status 404 specifically. - The string
"client error"for any other 4xx. - The string
"retry later"for any 5xx. - Raise
ValueError(f"unexpected status: {status}")for anything else (1xx, 3xx).
The starter has four responses to pass through. Use the bottom loop as-is.
Expected output:
{'id': 7}
not found
client error
retry later
this step needs the editor
on desktop today; in the app (coming soon). save your spot and we'll bring you back here when you're ready.