首页 > 解决方案 > 捕获请求异常的问题

问题描述

我正在向网络服务器创建删除请求并尝试捕获如下异常:

 try:
    response = req.delete(path, auth=HTTPBasicAuth(config.user(), config.password()), params=params, headers=headers, verify=True)
except requests.HTTPError as he:
    raise SystemExit(he)
except requests.ConnectionError as ce:
    raise SystemExit(ce)
except requests.URLRequired as ue:
    raise SystemExit(ue)
except requests.Timeout as te:
    raise SystemExit(te)
except requests.RequestException as err:
    print('Undefined error: ', err)

print(response.status_code)

但是 delete 没有被处理和response.status_code打印400,但是错误处理不起作用。任何想法为什么错误处理在那里不起作用?

标签: python-2.7python-requests

解决方案


如果你想捕获http错误(例如401 Unauthorized)来引发异常,你需要调用Response.raise_for_status。如果响应是 http 错误,这将引发 HTTPError。

try:
    response = req.delete(path, auth=HTTPBasicAuth(config.user(), config.password()), params=params, headers=headers, verify=True)
except requests.HTTPError as he:
    raise SystemExit(he)

推荐阅读