Skip to content

Improve error handling for HTTP response errors and exception handling for JSON parse parsing in fetch() #37

@kevinjwalters

Description

@kevinjwalters

fetch makes an HTTP request but does not currently check the HTTP status code. This could be a 5xx error and there's no specific handling for this.

Fifth post on Adafruit Forums: Adafruit CircuitPython and MicroPython: NASA image partially blank on PyPortal has an example of the current error handling too. There is no specific check for an appropriate Content-Type for json, the code optimstically tries to parse the response body and at the moment the exception handling does not cover the KeyError case:

Retrieving data...Reply is OK!
{'code': 500, 'msg': 'Internal Service Error', 'service_version': 'v1'}
Traceback (most recent call last):
File "code.py", line 38, in <module>
File "code.py", line 35, in <module>
File "adafruit_pyportal.py", line 696, in fetch
File "adafruit_pyportal.py", line 693, in fetch
File "adafruit_pyportal.py", line 517, in _json_traverse
KeyError: title

Possible that this line was intended to be only printed for debug too? A useful enhancement would be to print the HTTP status code and if present the response Content-Length:

print("Reply is OK!")

4xx errors are also worth considering particularly because broken servers may 404 requests and buggy servers occasionally respond with a 400, etc. 418 handling could also be considered.

Handling of failures of the adafruit.io services like image converter could also be handled better. I believe that's the cause of KeyError: content-length as discussed in Adafruit Forums: Adafruit CircuitPython and MicroPython: KeyError: content-length.

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions