错误处理

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: # 哎呀,出问题了
else: # 一切正常,处理响应

连接错误

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: 导入 requests 库的异常 from requests.exceptions import ConnectionError, HTTPError
try:
r = requests.get("http://api.music-catalog.com/albums")
# 2: 对错误状态码抛出异常 r.raise_for_status()
print(r.status_code)
# 3: 捕获连接错误 except ConnectionError as conn_err: print(f'Connection Error! {conn_err}.')
# 4: 捕获来自 API 服务器的错误响应 except HTTPError as http_err: print(f'HTTP error occurred: {http_err}')
Python 中的 API 入门

让我们练习!

Python 中的 API 入门

Preparing Video For Download...