question 267 Inheritance & Composition · medium
API errors and when to retry
A client for a code-hosting API turns failed responses into exceptions. Build the family: ApiError (keeps the status code), ClientError for 4xx statuses with two special cases NotFound (404) and RateLimited (429), and ServerError for 5xx. Then write error_for(status, message), which returns (doesn't raise) the most specific exception, and should_retry(err), which is True only for server errors and rate limits.
Classes
ApiError(Exception) with __init__(status, message) storing status (its text is "<status>: <message>"); ClientError and ServerError subclass ApiError; NotFound and RateLimited subclass ClientError`error_for(status, message)`404 → NotFound, 429 → RateLimited, other 400–499 → ClientError, 500–599 → ServerError; any other status → ValueError
`should_retry(err)`True for a ServerError or a RateLimited, False for any other error