Police-Data-Accessibility-Project / data-sources-app

An API and UI for using and maintaining the Data Sources database
MIT License
2 stars 4 forks source link

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

Open maxachis opened 1 week ago

maxachis commented 1 week ago

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.