[파이썬] requests 커스텀 에러 핸들링

Handling errors is an essential part of any application, and when it comes to making HTTP requests, the popular Python library requests provides an intuitive and convenient way to handle errors. In this blog post, we will explore how to implement custom error handling with requests to gracefully handle different types of errors that can occur during an HTTP request.

Why Custom Error Handling?

By default, requests provides a set of built-in exceptions for common HTTP errors such as ConnectionError, Timeout, and HTTPError. While these built-in exceptions cover many scenarios, there may be cases where you want finer control over error handling. Custom error handling allows you to define your own error classes and handle specific errors in a more granular way, providing a better user experience and clearer error messages.

Creating Custom Error Classes

To handle custom errors, we will create a subclass of the HTTPError class provided by requests.exceptions. This allows us to define our own error classes that inherit the behavior of the base class while adding additional functionalities.

Here’s an example of how to define a custom error class for a “404 Not Found” error:

import requests

class NotFoundError(requests.exceptions.HTTPError):
    pass

In this example, we create a NotFoundError class that inherits from HTTPError. This new class allows us to customize the behavior of handling “404 Not Found” errors.

Handling Custom Errors

Once we have defined our custom error classes, we can use try-except blocks to handle specific errors and provide appropriate responses.

Let’s continue with the example of the NotFoundError class. We will use the GET method from requests to make an HTTP request and handle the “404 Not Found” error:

import requests

class NotFoundError(requests.exceptions.HTTPError):
    pass

try:
    response = requests.get('https://example.com/nonexistent-url')
    response.raise_for_status()
except NotFoundError:
    print("The requested resource was not found.")
except requests.exceptions.HTTPError:
    print("Unhandled HTTP error occurred.")
except requests.exceptions.RequestException:
    print("An error occurred while making the request.")

In this code snippet, we try to make a GET request to an invalid URL. If a “404 Not Found” error occurs, the NotFoundError exception will be raised and caught by the corresponding except block, allowing us to handle the error in a customized way. If any other HTTP error or a general request exception occurs, it will be caught by the appropriate except block and display a generic error message.

Conclusion

Custom error handling with requests provides a way to handle HTTP errors in a more controlled and customized manner. By defining your own error classes and using try-except blocks, you can gracefully handle specific errors and provide meaningful feedback to the users of your application.

Remember to consider the different types of errors that can occur during an HTTP request and design your error handling logic accordingly. With custom error handling, you can improve the user experience and make your code more robust when working with requests.