|
| 1 | +# Error handling |
| 2 | + |
| 3 | +For incorrect or failed requests the Exonet API will return exceptions or errors. In most cases this will be because |
| 4 | +invalid data is provided (validation) or because the authenticated user does not have the right permissions to make |
| 5 | +the request. These exceptions can be handled in the following way. |
| 6 | + |
| 7 | +## Default exception behavior |
| 8 | +A failed request will result in an exception containing the error message. The following example has no custom error |
| 9 | +handling and will throw an exception when the request fails. |
| 10 | +```python |
| 11 | +from exonetapi import Client |
| 12 | + |
| 13 | +# Create a new Client. |
| 14 | +client = Client('https://api.exonet.nl') |
| 15 | + |
| 16 | +# Login with machine token. |
| 17 | +client.authenticator.set_token('INVALID_TOKEN') |
| 18 | + |
| 19 | +# Try to make a request, will fail due to invalid token. |
| 20 | +myDetails = client.resource('me').get() |
| 21 | +``` |
| 22 | + |
| 23 | +## Catching exceptions and outputting errors |
| 24 | +For validation exceptions you might be interested in the response body, since this can contain detail information about |
| 25 | +why the request was invalid. Catch the exception and output the request body containing the validation exception. |
| 26 | + |
| 27 | +```python |
| 28 | +from exonetapi import Client |
| 29 | +# Import the exception to catch. |
| 30 | +from requests.exceptions import HTTPError |
| 31 | + |
| 32 | +# Create a new Client. |
| 33 | +client = Client('https://api.exonet.nl') |
| 34 | + |
| 35 | +# Login with machine token. |
| 36 | +client.Authenticator.set_token('A_PREVIOUSLY_OBTAINED_TOKEN') |
| 37 | + |
| 38 | +try: |
| 39 | + # Try to get a certificate while providing an invalid ID. |
| 40 | + certificate = client.request('certificates').id('invalidID').get() |
| 41 | +except HTTPError as e: |
| 42 | + print(e.response.text) |
| 43 | + raise e |
| 44 | +``` |
| 45 | + |
| 46 | +This will output the request body where the details of the error can be found: |
| 47 | +``` |
| 48 | +{"errors":[{"status":400,"code":"101.10002","title":"request.invalidId","detail":"The id provided for 'certificate' is invalid.","variables":[]}]} |
| 49 | +
|
| 50 | +requests.exceptions.HTTPError: 400 Client Error: Bad Request for url: https://api.exonet.nl/certificates/invalidID |
| 51 | +``` |
| 52 | + |
| 53 | +--- |
| 54 | + |
| 55 | +[Back to the index](index.md) |
0 commit comments