Issue
One of the porposes of exception’s message is to help the developer to identify the root cause of the bug and fix it.
Currently, JSONDecodeError
doesn’t do it well enough.
Consider the following example:
import json
import requests
try:
server_raw_response = requests.get(url)
server_json_response = json.loads(server_raw_response)
except JSONDecodeError as error:
print(error)
# JSONDecodeError: Expecting , delimiter: line 1 column 23 (char 22)
Can you understand what is the root issue?
You can see that there is a problem with loading the data into json that needs ‘,’ in some character location.
But what actually caused the exception? What was the data that did it exactly?
In order to answer this question you would need to see data itself, right?
So you would go and print/log the data itself which caused the bug and then understand what you need to do.
As you can see, the error you’re getting isn’t indecative enough to understand what really the bug is.
Proposition
I would like to propose a simple solution to this:
import json
import requests
try:
server_raw_response = requests.get(url)
server_json_response = json.loads(server_raw_response)
except JSONDecodeError as error:
print(error.verbose())
# JSONDecodeError: Expecting , delimiter: line 1 column 23 (char 22), got: "'status': 200 'data': 3}"
Using the new verbose
function from the JSONDecodeError
class you get a verbose exeception message.
This message shows the data itself that caused the bug. You can even control the amount of context to get, by specifing the range of characters to show around the error.
The implementations of the solution don’t necessarily need to be as I suggested.
The important part is that you will have an easy and clear error message.
Benefits
• Easy to debug - verbose and clear error message.
• Easy to use - built-in function to get the verbose error message.
• Data efficiency - The amount of context of the error is controlled by the user.
• Backwards compatibility: this change is fully backwards compatible since the proposed feature will only add function to JSONDecodeError
(not removing or changing)