錯誤處理

Python API 入門

Chris Ramakers

Engineering Manager

錯誤狀態碼

4xx 用戶端錯誤


  • 表示用戶端端的問題
  • 常見原因:不當請求、驗證失敗等

解法:修正請求

5xx 伺服器錯誤


  • 源自伺服器端問題
  • 常見原因:伺服器過載、設定錯誤、內部錯誤

解法:由 API 管理員修復

Python API 入門

錯誤狀態碼:範例

4xx 用戶端錯誤


  • 401 Unauthorized - 此請求缺少目標資源所需的有效驗證資訊
  • 404 Not Found - 伺服器找不到所請求的資源
  • 429 Too Many Requests - 用戶端在短時間內送出太多請求

5xx 伺服器錯誤


  • 500 Internal Server Error - 伺服器發生非預期問題而無法回應
  • 502 Bad Gateway - API 伺服器無法成功連到完成回應所需的其他伺服器
  • 504 Gateway Timeout - 作為閘道的伺服器未及時收到上游伺服器回應
Python API 入門

處理錯誤

API 錯誤

import requests

url = 'http://api.music-catalog.com/albums'

r = requests.get(url)

if r.status_code >= 400: # Oops, something went wrong
else: # All fine, let's do something # with the response

連線錯誤

import requests

from requests.exceptions import ConnectionError
url = ''
try: r = requests.get(url) print(r.status_code)
except ConnectionError as conn_err: print(f'Connection Error! {conn_err}.') print(error)
Python API 入門

raise_for_status()

import requests

# 1: Import the requests library exceptions from requests.exceptions import ConnectionError, HTTPError
try:
r = requests.get("http://api.music-catalog.com/albums")
# 2: Enable raising exceptions for returned error statuscodes r.raise_for_status()
print(r.status_code)
# 3: Catch any connection errors except ConnectionError as conn_err: print(f'Connection Error! {conn_err}.')
# 4: Catch error responses from the API server except HTTPError as http_err: print(f'HTTP error occurred: {http_err}')
Python API 入門

一起來練習吧!

Python API 入門

Preparing Video For Download...