Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Refactor middleware code which returns empty results to signal failure to instead throw exceptions to be handled #336

Closed
maxachis opened this issue Jun 22, 2024 · 0 comments · Fixed by Police-Data-Accessibility-Project/data-sources-app-v2#50
Labels
fixed_in_dev This is merged into the dev environment and waiting to be merged into main refactor Improve the code without changing the underlying logic

Comments

@maxachis
Copy link
Contributor

maxachis commented Jun 22, 2024

At several parts of the code, empty results are returned in the case of failure, which is then handled in subsequent code. For example, in data_source_by_id_query in middleware/data_source_queries.py:

def data_source_by_id_query(
    data_source_id: str,
    cursor: psycopg2.extensions.cursor,
) -> Dict[str, Any]:
# ...
    result = data_source_by_id_results(cursor, data_source_id)
    if not result:
        return []

And then in data_source_by_id_wrapper, which calls this:

def data_source_by_id_wrapper(arg, conn: PgConnection) -> Response:
    data_source_details = data_source_by_id_query(data_source_id=arg, cursor=conn)
    if data_source_details:
        return make_response(data_source_details, HTTPStatus.OK.value)
    else:
        return make_response({"message": "Data source not found."}, HTTPStatus.OK.value)

Code like this poses a few problems:

  1. This result does not match the type normally returned by this object -- having a function that normally returns a dictionary instead return a list is odd.
  2. It is unclear. From the perspective of someone calling this function, an empty list being returned does not indicate much. A custom exception, on the other hand, is much more clear about what exactly occurred in the called function.

Thus, in cases like this in the code where an empty value is returned to signal failure, a custom exception should instead be thrown, which is then handled in functions calling it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
fixed_in_dev This is merged into the dev environment and waiting to be merged into main refactor Improve the code without changing the underlying logic
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants