ai-cfia / ailab-datastore

This is a repo representing the data layer of multiple ailab projects
MIT License
2 stars 0 forks source link

issue #106: improve exception handling in `fertiscan` #199

Closed k-allagbe closed 3 weeks ago

k-allagbe commented 1 month ago

Changes:

Query exceptions hierarchy:

    Exception
    |__QueryError
       |__InspectionQueryError
       |__LabelInformationQueryError
       |__LabelDimensionQueryError
       |__MetricQueryError
       |__UnitQueryError
       |__ElementCompoundQueryError
       |__MicronutrientQueryError
       |__GuaranteedAnalysisQueryError
       |__OrganizationQueryError
       |__OrganizationInformationQueryError
       |__LocationQueryError
       |__RegionQueryError
       |__ProvinceQueryError
       |__SpecificationQueryError
       |__SubLabelQueryError
       |__SubTypeQueryError

Each QueryError sub type exception has specific errors related to creation, retrieval, updating, and deletion, as well as a 'not found' error.
Metadata exceptions hierarchy:

    Exception
    |__MetadataError
       |__BuildInspectionImportError
       |__BuildInspectionExportError
       |__NPKError

The code using a decorator:

```python
@handle_query_errors(LabelInformationRetrievalError)
def get_label_information_json(cursor, label_info_id) -> dict:
    query = """
        SELECT get_label_info_json(%s);
        """
    cursor.execute(query, (str(label_info_id),))
    label_info = cursor.fetchone()
    if label_info is None or label_info[0] is None:
        raise LabelInformationNotFoundError(
            "Error: could not get the label information: " + str(label_info_id)
        )
    return label_info[0]

is equivalent to:

def get_label_information_json(cursor, label_info_id) -> dict:
    try:
        query = """
            SELECT get_label_info_json(%s);
            """
        cursor.execute(query, (str(label_info_id),))
        label_info = cursor.fetchone()
        if label_info is None or label_info[0] is None:
            raise LabelInformationNotFoundError(
                "Error: could not get the label information: " + str(label_info_id)
            )
        return label_info[0]
    except QueryError:
        raise
    except Error as db_error:
        raise LabelInformationRetrievalError(f"Database error: {db_error}") from db_error
    except Exception as e:
        raise LabelInformationRetrievalError(f"Unexpected error: {e}") from e

Note that LabelInformationNotFoundError is a QueryError.

k-allagbe commented 3 weeks ago

This issue will not fix #108 as that is core datastore code that might affect nachet.