python 各种HTTP响应异常码并自定义异常信息
在Python中,处理HTTP响应状态码并根据不同的状态码抛出不同的异常,可以帮助你更好地管理和调试HTTP请求。你可以使用requests
库来发送HTTP请求,并基于响应状态码抛出相应的异常。以下是一个示例代码,展示了如何根据HTTP响应状态码抛出各种异常:
import requests
class HTTPError(Exception):
"""Base class for HTTP-related exceptions."""
pass
class HTTPBadRequestError(HTTPError):
"""Exception raised for 400 Bad Request errors."""
pass
class HTTPUnauthorizedError(HTTPError):
"""Exception raised for 401 Unauthorized errors."""
pass
class HTTPForbiddenError(HTTPError):
"""Exception raised for 403 Forbidden errors."""
pass
class HTTPNotFoundError(HTTPError):
"""Exception raised for 404 Not Found errors."""
pass
class HTTPServerError(HTTPError):
"""Exception raised for 500 Internal Server Error and other 5xx errors."""
pass
def raise_for_status(response):
"""
Raises an appropriate HTTPError subclass based on the HTTP status code.
:param response: The response object from a requests.get/post/etc. call.
:raises HTTPError: The appropriate subclass of HTTPError based on status code.
"""
if response.status_code == 400:
raise HTTPBadRequestError(f"Bad Request: {response.text}")
elif response.status_code == 401:
raise HTTPUnauthorizedError(f"Unauthorized: {response.text}")
elif response.status_code == 403:
raise HTTPForbiddenError(f"Forbidden: {response.text}")
elif response.status_code == 404:
raise HTTPNotFoundError(f"Not Found: {response.text}")
elif 500 <= response.status_code < 600:
raise HTTPServerError(f"Server Error ({response.status_code}): {response.text}")
# Optionally, you can handle other status codes here
response.raise_for_status() # This will raise for any other unknown status codes
# Example usage
try:
url = 'https://api.example.com/resource/123'
response = requests.get(url)
raise_for_status(response)
# If no exception is raised, process the response data
data = response.json()
print(data)
except HTTPError as e:
print(f"HTTP error occurred: {e}")