出問題的時候
像工程師一樣診斷 API 錯誤,而不是亂猜
⏱ 預估 ~6 分鐘
01 · 讀一讀
API 會壞、Server 會掛、Key 會過期、流量限制會碰到、URL 會打錯字。
新手跟工程師的差別不是會不會出狀況 — 而是你診斷跟修復的速度。
系統化做法:
1. 讀 status code — 哪個錯誤類別? 2. 讀回應主體 — server 通常會明說哪裡錯 3. 看 header — Retry-After、WWW-Authenticate、X-RateLimit-* 都是寶藏 4. 檢查 URL — 一個錯字什麼都壞
重點整理
- Debug 永遠用 curl -i — 你需要看 header
- 錯誤主體通常比狀態碼有用
- 4xx = 你的問題。5xx = 他們的問題。
- 什麼都試不出來,就看 API 提供者的狀態頁
02 · 看程式碼
依狀態碼類別的診斷清單。
4xx — Client 錯誤(你做錯了)
400 Bad Request
→ Check: Is your JSON valid? Are required fields present?
→ Fix: Validate your -d body. Check the API docs for required fields.
401 Unauthorized
→ Check: Did you include the Authorization header? Is the key correct?
→ Fix: Check your API key. Make sure you're using the right header format.
403 Forbidden
→ Check: Do you have permission? Is this feature on your plan?
→ Fix: Check your account permissions or upgrade your plan.
404 Not Found
→ Check: Does the URL path exist? Did you replace all {placeholders}?
→ Fix: Double-check the URL against the docs. Check the resource ID.
429 Too Many Requests
→ Check: Look for Retry-After header — it tells you when to retry.
→ Fix: Slow down. Implement exponential backoff. Use caching.
5xx — Server 錯誤(他們的問題)
500 Internal Server Error
→ Their code crashed. Check their status page.
→ Retry after a brief wait.
503 Service Unavailable
→ Server is overloaded or in maintenance.
→ Check their status page. Wait and retry.
504 Gateway Timeout
→ Your request took too long. The server gave up.
→ Try again. If persistent, contact the API provider.
curl 錯誤(連回應都還沒收到)
curl: (6) Could not resolve host
→ DNS failure. Check the hostname for typos.
→ Verify your internet connection.
curl: (7) Failed to connect
→ Server unreachable or port blocked.
→ Check if the service is down.
curl: (35) SSL certificate problem
→ Certificate expired or invalid.
→ Check if you're using https:// correctly.
03 · 真機練習
對一個不存在的 GitHub repo 發請求,觸發真實的 404。
curl -i https://api.github.com/repos/this-user-doesnt-exist-xyz/no-such-repo
04 · 真機練習
對需要驗證的 endpoint 發沒驗證的請求,觸發真實的 401。
curl -i https://api.github.com/user
05 · 選擇題
你呼叫 API 拿到 429 狀態碼。該做什麼?
- 檢查你的 API key
- 換 URL
- 改用 POST 請求
- 等一下再試 — 你打到 rate limit
06 · 填空
4 開頭的狀態碼表示錯誤在 _____ 那邊(你的請求錯了)。
⚠ 完整互動體驗需要 JavaScript。請啟用 JavaScript 後重新整理。
※ 本站為獨立繁中教學專案,非 Anthropic 官方產品。Claude™ 為 Anthropic, PBC 商標。