Problem
I have a Python library which sends XML requests to an external API. If an issue occurs, the API responds with an error containing an error code and description with error details.
These errors can be caused by anything from malformed XML data, an invalid username/password, editing a read-only attribute, or trying to load data that doesn't exist.
<Response Status="Failure" Action="LoadByName">
<Error Message="WFP-00235 The job name does not exist in the database." ErrorCode="17" AtIndex="0"/>
</Response>
Current approach
Because I can't control the response I'll receive, my library currently handles any exceptions by raising a RuntimeError
with the message received from the API.
import xml.etree.ElementTree as ElementTree
def parse_response(xml):
# Check if XML response contains any errors
if xml.find(".//Error") is not None:
raise RuntimeError(xml.find(".//Error").get("Message"))
...
RuntimeError: WFP-00235 The job name does not exist in the database.
One major flaw with this approach is that the ErrorCode
isn't preserved when an exception is raised. This makes it impossible to catch specific API errors, as each error is essentially a generic exception.
Question
How should I handle XML errors that come from an external API? Can I raise/catch errors based on their numeric ErrorCode?
Failure
responses include an<Error>
element, so a more generic exception would be good to have. – Stevoisiak Feb 1 '18 at 18:59