python: Catch specific exceptions from orjson.

Followup to #16120.

Signed-off-by: Anders Kaseorg <anders@zulip.com>
This commit is contained in:
Anders Kaseorg 2020-10-08 17:17:33 -07:00 committed by Tim Abbott
parent a109d68af0
commit aabef3d9be
6 changed files with 11 additions and 10 deletions

View File

@ -41,7 +41,7 @@ def encode_info(info: Any) -> str:
try:
info = orjson.loads(info)
result = '(stringified)\n'
except Exception:
except orjson.JSONDecodeError:
pass
result += html.escape(pprint.pformat(info, indent=4))
return '<pre>' + result + '</pre>'

View File

@ -2039,7 +2039,7 @@ def extract_stream_indicator(s: str) -> Union[str, int]:
try:
data = orjson.loads(s)
except (ValueError, TypeError):
except orjson.JSONDecodeError:
# If there was no JSON encoding, then we just
# have a raw stream name.
return s
@ -2067,7 +2067,7 @@ def extract_private_recipients(s: str) -> Union[List[str], List[int]]:
try:
data = orjson.loads(s)
except (ValueError, TypeError):
except orjson.JSONDecodeError:
data = s
if isinstance(data, str):
@ -2388,7 +2388,7 @@ def check_message(sender: UserProfile, client: Client, addressee: Addressee,
if widget_content is not None:
try:
widget_content = orjson.loads(widget_content)
except Exception:
except orjson.JSONDecodeError:
raise JsonableError(_('Widgets: API programmer sent invalid JSON content'))
try:

View File

@ -347,7 +347,7 @@ def has_request_variables(view_func: ViewFuncT) -> ViewFuncT:
if param.validator is not None and not default_assigned:
try:
val = orjson.loads(val)
except Exception:
except orjson.JSONDecodeError:
raise JsonableError(_('Argument "{}" is not valid JSON.').format(post_var_name))
try:

View File

@ -745,7 +745,7 @@ Output:
"""
try:
json = orjson.loads(result.content)
except Exception: # nocoverage
except orjson.JSONDecodeError: # nocoverage
json = {'msg': "Error parsing JSON in response!"}
self.assertEqual(result.status_code, 200, json['msg'])
self.assertEqual(json.get("result"), "success")
@ -758,7 +758,7 @@ Output:
def get_json_error(self, result: HttpResponse, status_code: int=400) -> Dict[str, Any]:
try:
json = orjson.loads(result.content)
except Exception: # nocoverage
except orjson.JSONDecodeError: # nocoverage
json = {'msg': "Error parsing JSON in response!"}
self.assertEqual(result.status_code, status_code, msg=json.get('msg'))
self.assertEqual(json.get("result"), "error")

View File

@ -21,7 +21,7 @@ def process_submessage(request: HttpRequest,
try:
orjson.loads(content)
except Exception:
except orjson.JSONDecodeError:
return json_error(_("Invalid json for submessage"))
do_add_submessage(

View File

@ -14,6 +14,7 @@
# matching the args/kwargs passed in the authenticate() call.
import binascii
import copy
import json
import logging
from abc import ABC, abstractmethod
from typing import Any, Callable, Dict, List, Optional, Set, Tuple, Type, TypeVar, Union, cast
@ -1429,7 +1430,7 @@ class GitHubAuthBackend(SocialAuthMixin, GithubOAuth2):
access_token = kwargs["response"]["access_token"]
try:
emails = self._user_data(access_token, '/emails')
except (HTTPError, ValueError, TypeError): # nocoverage
except (HTTPError, json.JSONDecodeError): # nocoverage
# We don't really need an explicit test for this code
# path, since the outcome will be the same as any other
# case without any verified emails
@ -1812,7 +1813,7 @@ class SAMLAuthBackend(SocialAuthMixin, SAMLAuth):
# IdP-initiated sign in. Right now we only support transporting subdomain through json in
# RelayState, but this format is nice in that it allows easy extensibility here.
return {'subdomain': data.get('subdomain')}
except (ValueError, TypeError):
except orjson.JSONDecodeError:
return {}
def choose_subdomain(self, relayed_params: Dict[str, Any]) -> Optional[str]: