python: Catch JSONDecodeError instead of ValueError when decoding JSON.

These weren’t wrong since orjson.JSONDecodeError subclasses
json.JSONDecodeError which subclasses ValueError, but the more
specific ones express the intention more clearly.

(ujson raised ValueError directly, as did json in Python 2.)

Signed-off-by: Anders Kaseorg <anders@zulip.com>
This commit is contained in:
Anders Kaseorg 2020-08-12 11:23:23 -07:00 committed by Tim Abbott
parent 2e97d2b9f7
commit d0f4af5f8c
10 changed files with 11 additions and 11 deletions

View File

@ -107,7 +107,7 @@ def custom_headers(headers_json: str) -> Dict[str, str]:
return {} return {}
try: try:
return orjson.loads(headers_json) return orjson.loads(headers_json)
except ValueError as ve: except orjson.JSONDecodeError as ve:
raise argparse.ArgumentTypeError( raise argparse.ArgumentTypeError(
'Encountered an error while attempting to parse custom headers: {}\n' 'Encountered an error while attempting to parse custom headers: {}\n'
'Note: all strings must be enclosed within "" instead of \'\''.format(ve)) 'Note: all strings must be enclosed within "" instead of \'\''.format(ve))

View File

@ -286,7 +286,7 @@ def log_exception_to_webhook_logger(
if request.content_type == 'application/json': if request.content_type == 'application/json':
try: try:
payload = orjson.dumps(orjson.loads(payload), option=orjson.OPT_INDENT_2).decode() payload = orjson.dumps(orjson.loads(payload), option=orjson.OPT_INDENT_2).decode()
except ValueError: except orjson.JSONDecodeError:
request_body = str(payload) request_body = str(payload)
else: else:
request_body = str(payload) request_body = str(payload)

View File

@ -272,7 +272,7 @@ def process_success_response(event: Dict[str, Any],
response: Response) -> None: response: Response) -> None:
try: try:
response_json = json.loads(response.text) response_json = json.loads(response.text)
except ValueError: except json.JSONDecodeError:
fail_with_message(event, "Invalid JSON in response") fail_with_message(event, "Invalid JSON in response")
return return

View File

@ -297,7 +297,7 @@ def has_request_variables(view_func: ViewFuncT) -> ViewFuncT:
if param.argument_type == 'body': if param.argument_type == 'body':
try: try:
val = orjson.loads(request.body) val = orjson.loads(request.body)
except ValueError: except orjson.JSONDecodeError:
raise InvalidJSONError(_("Malformed JSON")) raise InvalidJSONError(_("Malformed JSON"))
kwargs[func_var_name] = val kwargs[func_var_name] = val
continue continue

View File

@ -183,7 +183,7 @@ class ZulipTestCase(TestCase):
return return
try: try:
content = orjson.loads(result.content) content = orjson.loads(result.content)
except ValueError: except orjson.JSONDecodeError:
return return
json_url = False json_url = False
if url.startswith('/json'): if url.startswith('/json'):

View File

@ -56,7 +56,7 @@ approach shown above.
return {} return {}
try: try:
custom_headers_dict = orjson.loads(custom_headers) custom_headers_dict = orjson.loads(custom_headers)
except ValueError as ve: except orjson.JSONDecodeError as ve:
raise CommandError('Encountered an error while attempting to parse custom headers: {}\n' raise CommandError('Encountered an error while attempting to parse custom headers: {}\n'
'Note: all strings must be enclosed within "" instead of \'\''.format(ve)) 'Note: all strings must be enclosed within "" instead of \'\''.format(ve))
return standardize_headers(custom_headers_dict) return standardize_headers(custom_headers_dict)

View File

@ -482,7 +482,7 @@ def load_event_queues(port: int) -> None:
data = orjson.loads(stored_queues.read()) data = orjson.loads(stored_queues.read())
except FileNotFoundError: except FileNotFoundError:
pass pass
except ValueError: except orjson.JSONDecodeError:
logging.exception("Tornado %d could not deserialize event queues", port, stack_info=True) logging.exception("Tornado %d could not deserialize event queues", port, stack_info=True)
else: else:
try: try:

View File

@ -66,7 +66,7 @@ def get_fixtures(request: HttpResponse,
body = f.read() body = f.read()
try: try:
body = orjson.loads(body) body = orjson.loads(body)
except ValueError: except orjson.JSONDecodeError:
pass # The file extension will be used to determine the type. pass # The file extension will be used to determine the type.
headers_raw = get_fixture_http_headers(valid_integration_name, headers_raw = get_fixture_http_headers(valid_integration_name,
@ -91,7 +91,7 @@ def check_send_webhook_fixture_message(request: HttpRequest,
custom_headers: str=REQ()) -> HttpResponse: custom_headers: str=REQ()) -> HttpResponse:
try: try:
custom_headers_dict = orjson.loads(custom_headers) custom_headers_dict = orjson.loads(custom_headers)
except ValueError as ve: except orjson.JSONDecodeError as ve:
return json_error(f"Custom HTTP headers are not in a valid JSON format. {ve}") # nolint return json_error(f"Custom HTTP headers are not in a valid JSON format. {ve}") # nolint
response = send_webhook_fixture_message(url, body, is_json, response = send_webhook_fixture_message(url, body, is_json,

View File

@ -146,7 +146,7 @@ def api_librato_webhook(request: HttpRequest, user_profile: UserProfile,
payload: Dict[str, Any]=REQ(converter=orjson.loads, default={})) -> HttpResponse: payload: Dict[str, Any]=REQ(converter=orjson.loads, default={})) -> HttpResponse:
try: try:
attachments = orjson.loads(request.body).get('attachments', []) attachments = orjson.loads(request.body).get('attachments', [])
except ValueError: except orjson.JSONDecodeError:
attachments = [] attachments = []
if not attachments and not payload: if not attachments and not payload:

View File

@ -31,7 +31,7 @@ def api_slack_incoming_webhook(request: HttpRequest, user_profile: UserProfile,
if payload is None: if payload is None:
try: try:
payload = orjson.loads(request.body) payload = orjson.loads(request.body)
except ValueError: # nocoverage except orjson.JSONDecodeError: # nocoverage
raise InvalidJSONError(_("Malformed JSON")) raise InvalidJSONError(_("Malformed JSON"))
if user_specified_topic is None and "channel" in payload: if user_specified_topic is None and "channel" in payload: