In this lesson, you will learn how to create predictable, informative error interfaces that help users of your modules understand exactly what went wrong without exposing sensitive internal details.
The Problem with Generic Errors
When you build a module, simply raising a standard ValueError or TypeError can be frustrating for API users. These errors lack context. A defensive API design focuses on standardization: users should be able to rely on a consistent structure, whether they are catching an error from your math module or your data-loading module.
Standardizing the Interface
A defensive interface uses custom exception hierarchies to categorize errors. Instead of a "catch-all" approach, you provide specific exceptions that carry meaningful metadata. By using __init__ in your custom exception classes, you can enforce that every error includes an error code or a specific request ID, making debugging easier for the person using your code.
Consider this structure:
class APIError(Exception):
"""Base class for all module errors."""
def __init__(self, message, code):
super().__init__(message)
self.code = code
class ResourceNotFoundError(APIError):
"""Raised when a requested resource is missing."""
pass
# Usage inside your module:
def get_user_data(user_id):
if not user_exists(user_id):
raise ResourceNotFoundError("User not found in database", code="ERR_001")
Why This is Defensive
- Predictability: Users can look at your documentation and know exactly which exceptions to expect.
- Actionability: By attaching a
codeattribute, you allow the consuming code to react programmatically (e.g., retrying if the code isTIMEOUTversus failing if the code isINVALID_AUTH). - Encapsulation: You hide the internal stack trace details—like which specific database connection failed—and instead provide a clear, user-facing description.
By defining a common base class (APIError), you allow your users to catch all errors specific to your module with a single except APIError: block, while still providing the flexibility to handle specific scenarios like ResourceNotFoundError when needed.
Key Takeaway: A defensive API error interface uses a custom hierarchy and consistent metadata to ensure that users can reliably catch, identify, and respond to errors without needing to inspect internal implementation details.