richardogoma / bitcoin-rate-tracker

A web application or microservice for tracking and visualizing Bitcoin rates across major currencies.
MIT License
0 stars 1 forks source link

Error handling inconsistency invoking the API #36

Closed richardogoma-NLNG closed 1 year ago

richardogoma-NLNG commented 1 year ago

When the API is invoked at the /data endpoint or route with incomplete parameters, for example,

iwr "https://richardogoma.pythonanywhere.com/data?currency=USD"

The API throws a 500 Internal Server Error which isn't the fact. The API should rather return a 400 Bad Request Error which resulted because of this code section in the /api/routes.py file:

    # Define regex patterns for validation and extraction
    patterns = [
        (re.compile(r"^([a-zA-Z]{3})$"), currency),
        (re.compile(r"^([1-9]|[1-3][0-9]|4[0-8])h$"), timerange),
    ]

    params = [
        pattern.match(variable).group(1)
        for pattern, variable in patterns
        if pattern.match(variable)
    ]

    try:
        # Extract validated parameters
        rate_type = f"{params[0].lower()}_rate"
        minutes = int(params[1]) * 60

    except (IndexError, TypeError) as error_msg:
        return make_response(
            jsonify({"Bad Request": f"Provide valid query parameters, {error_msg}"}),
            400,
        )

The params list is outside the try-except block, and in this case, patterns returns:

[(re.compile(r'^([a-zA-Z]{3})$', re.UNICODE), 'USD'),
 (re.compile(r'^([1-9]|[1-3][0-9]|4[0-8])h$', re.UNICODE), None)]

So, you cannot perform a REGEX match operation on a NoneType, so this returns a TypeError that isn't handled by the code, and so the server throws a misleading error message.

Update the code to capture the params list definition in the try-except block also.