I am a beginner in Python, but I have referred several questions related to individually handling error messages in Python and I've also read best practices of raising exceptions. However, this is more of a design question to handle error messages when a single function is used to process/validate errors.
There are individual functions that make different API calls. To handle the response, all these functions use the following generic function:
def print_if_error_and_exit(response, debug, message_override_map=None, exit_on_failure=True):
if hasattr(response, 'status') and (response.status < 200 or response.status >= 300):
overriden_message = message_override_map.get(response.status) if message_override_map else None
if overriden_message:
error_message = overriden_message
elif hasattr(response, 'message'):
error_message = response.message
else:
error_message = 'No error message found'
if exit_on_failure:
print_error_message('Error (HTTP {0}): {1}'.format(response.status, error_message))
if debug:
print_error_message(repr(response))
sys.exit(1)
else:
raise ResponseException(error_message)
Now, we want to retain this function but also have a capability to provide custom, API-specific human-friendly error messages. One of doing that would be to call this function with a dict
that can take HTTP status code along with the customized message. However, this might not be the best approach, and I was wondering if there was a better way of achieving this objective.
Aucun commentaire:
Enregistrer un commentaire