promptdojo_

Status codes and error handling — what AI's API calls do when the wire blinks — step 9 of 9

Checkpoint

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 body if 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

full-screen editor opens — close anytime to keep reading.