# AUTOGENERATED! DO NOT EDIT! File to edit: ../nbs/01_errs.ipynb.

# %% auto 0
__all__ = ['RateLimitError']

# %% ../nbs/01_errs.ipynb 4
import sys, time
from urllib.error import HTTPError
from typing import Callable

# %% ../nbs/01_errs.ipynb 5
from .cons import RATE_LIMIT, RETRY_AFTER

# %% ../nbs/01_errs.ipynb 7
class RateLimitError(HTTPError):
    def __init__(self, err: HTTPError, endpoint: str, retry: float = RATE_LIMIT):
        super().__init__(err.url, err.code, err.reason, err.headers, err.fp)
        self.endpoint = endpoint
        self.retry = retry
    
    def handle(self, callback: Callable, **params):
        match self.code:
            case 429:
                retry = self.headers.get(RETRY_AFTER, self.retry)
                time.sleep(float(retry))
                callback(self.endpoint, self.headers, params)
            case _:
                sys.stderr.write(f'Request failed for {self.endpoint}: Status code: {self.code} Reason: {self.reason}\n')
