FOLIO-FSE / FolioClient

A python module that provides a client class to manage interaction with the FOLIO Library Services Platform APIs
MIT License
7 stars 7 forks source link

[Improvement] Add custom exceptions #11

Open JensHeinrich opened 1 year ago

JensHeinrich commented 1 year ago

Returning Subclasses of the ValueError for the different http statuscodes would make the usage of FolioClient as a library easier.

bltravis commented 1 week ago

@JensHeinrich I know it's been a while since you posted this, but can I ask why just handling the httpx.HTTPStatusError exception wouldn't work? I'm not opposed to creating custom exceptions, but I think that throwing actual status errors is cleaner than wrapping them in another exception type.

JensHeinrich commented 1 week ago

For most APIs we have a list of predefined combinations of status codes, their media type and possibly their JSON-Schema; using those as custom error types would make many code options immediately more clear, i.e. for https://s3.amazonaws.com/foliodocs/api/mod-users-bl/p/mod-users-bl.html#bl_users_by_id__id__delete

there could be errors as follows (based on HTTPStatusError because this might be more universal)

class MissingUserIDError(httpx.HTTPStatusError):
     """user with a given ID not found."""

class OpenTransactionsError(httpx.HTTPStatusError):
    """Open transactions bound to user."""
   json: Annotated[object, Doc("Data conforming to the 'User Transactions Schema')]

class InternalServerError(httpx.HTTPStatusError):
    """Internal server error, e.g. due to misconfiguration."""

And developers using the library could write code like:

try:
    DELETE_USER_BY_ID(id=ID)
except OpenTransactionsError as _open_transaction:
   logger.error(json.dumps({"id": ID, "data": _open_transactions.json }))
   raise
except MissingUserID:
    # Sometimes the deletion routine is called by multiple users, but deleted is deleted
    logger.debug(json.dumps({"already_missing": ID})) 

This is much clearer then catching all exceptions and checking the status code; additionally on the same level a library developer could distinguish between OKAPI and FOLIO-Level errors.

Using the predefined error models for the errors would also greatly help with typehints.