Python Requests HTTPError
If you are working with Python Requests module, you might encounter the HTTPError exception. This exception is raised when a request fails with an HTTP error status code, typically 4xx or 5xx.
The HTTPError exception is a subclass of the RequestException class and is raised when the request was unsuccessful and an error response was returned from the server.
Catching HTTPError
To catch the HTTPError exception, you need to include a try-except block in your code. Here's an example:
import requests
try:
response = requests.get("https://example.com/404")
response.raise_for_status()
except requests.exceptions.HTTPError as error:
print(error.response.status_code)
In this code, we are trying to send a GET request to a URL that returns a 404 status code. We are then calling the raise_for_status()
method of the Response object to check if the response was successful. If not, we catch the HTTPError exception and print the status code of the error response.
Handling HTTPError
Once you catch the HTTPError exception, you can handle it in various ways. Some common ways include:
- Printing the error message or status code
- Logging the error
- Raising a custom exception
Here's an example of how to log the error using Python's built-in logging module:
import logging
import requests
logger = logging.getLogger(__name__)
try:
response = requests.get("https://example.com/404")
response.raise_for_status()
except requests.exceptions.HTTPError as error:
logger.error(error.response.status_code)
In this code, we are creating a logger object using the logging.getLogger()
method. We then catch the HTTPError exception and log the status code of the error response using the logger's error()
method.
Conclusion
The HTTPError exception is a common exception that you might encounter when working with Python Requests module. By including a try-except block in your code and handling the exception appropriately, you can ensure that your code handles errors gracefully.