ruff: Fix B904 raise exceptions with raise ... from err.

Signed-off-by: Anders Kaseorg <anders@zulip.com>
This commit is contained in:
Anders Kaseorg 2023-11-01 19:54:56 -07:00
parent 158480fe2c
commit 8fc924cd12
5 changed files with 21 additions and 17 deletions

View file

@ -117,7 +117,7 @@ class MatrixToZulip:
) )
except Exception as exception: except Exception as exception:
# Generally raised when user is forbidden # Generally raised when user is forbidden
raise BridgeFatalZulipError(exception) raise BridgeFatalZulipError(exception) from exception
if result["result"] != "success": if result["result"] != "success":
# Generally raised when API key is invalid # Generally raised when API key is invalid
raise BridgeFatalZulipError(result["msg"]) raise BridgeFatalZulipError(result["msg"])
@ -459,7 +459,7 @@ def read_configuration(config_file: str) -> Dict[str, Dict[str, Any]]:
try: try:
config.read(config_file) config.read(config_file)
except configparser.Error as exception: except configparser.Error as exception:
raise BridgeConfigError(str(exception)) raise BridgeConfigError(str(exception)) from exception
if set(config.sections()) < {"matrix", "zulip"}: if set(config.sections()) < {"matrix", "zulip"}:
raise BridgeConfigError("Please ensure the configuration has zulip & matrix sections.") raise BridgeConfigError("Please ensure the configuration has zulip & matrix sections.")
@ -619,14 +619,16 @@ def write_sample_config(target_path: str, zuliprc: Optional[str]) -> None:
try: try:
zuliprc_config.read(zuliprc) zuliprc_config.read(zuliprc)
except configparser.Error as exception: except configparser.Error as exception:
raise BridgeConfigError(str(exception)) raise BridgeConfigError(str(exception)) from exception
try: try:
sample_dict["zulip"]["email"] = zuliprc_config["api"]["email"] sample_dict["zulip"]["email"] = zuliprc_config["api"]["email"]
sample_dict["zulip"]["site"] = zuliprc_config["api"]["site"] sample_dict["zulip"]["site"] = zuliprc_config["api"]["site"]
sample_dict["zulip"]["api_key"] = zuliprc_config["api"]["key"] sample_dict["zulip"]["api_key"] = zuliprc_config["api"]["key"]
except KeyError as exception: except KeyError as exception:
raise BridgeConfigError("You provided an invalid zuliprc file: " + str(exception)) raise BridgeConfigError(
"You provided an invalid zuliprc file: " + str(exception)
) from exception
sample: configparser.ConfigParser = configparser.ConfigParser() sample: configparser.ConfigParser = configparser.ConfigParser()
sample.read_dict(sample_dict) sample.read_dict(sample_dict)

View file

@ -650,7 +650,7 @@ class Client:
isinstance(e, requests.exceptions.SSLError) isinstance(e, requests.exceptions.SSLError)
and str(e) != "The read operation timed out" and str(e) != "The read operation timed out"
): ):
raise UnrecoverableNetworkError("SSL Error") raise UnrecoverableNetworkError("SSL Error") from e
if longpolling: if longpolling:
# When longpolling, we expect the timeout to fire, # When longpolling, we expect the timeout to fire,
# and the correct response is to just retry # and the correct response is to just retry
@ -658,13 +658,15 @@ class Client:
else: else:
end_error_retry(False) end_error_retry(False)
raise raise
except requests.exceptions.ConnectionError: except requests.exceptions.ConnectionError as e:
if not self.has_connected: if not self.has_connected:
# If we have never successfully connected to the server, don't # If we have never successfully connected to the server, don't
# go into retry logic, because the most likely scenario here is # go into retry logic, because the most likely scenario here is
# that somebody just hasn't started their server, or they passed # that somebody just hasn't started their server, or they passed
# in an invalid site. # in an invalid site.
raise UnrecoverableNetworkError("cannot connect to server " + self.base_url) raise UnrecoverableNetworkError(
"cannot connect to server " + self.base_url
) from e
if error_retry(""): if error_retry(""):
continue continue

View file

@ -34,7 +34,7 @@ class GiphyHandler:
data = requests.get(GIPHY_TRANSLATE_API, params=query) data = requests.get(GIPHY_TRANSLATE_API, params=query)
data.raise_for_status() data.raise_for_status()
except ConnectionError as e: except ConnectionError as e:
raise ConfigValidationError(str(e)) raise ConfigValidationError(str(e)) from e
except HTTPError as e: except HTTPError as e:
error_message = str(e) error_message = str(e)
if data.status_code == 403: if data.status_code == 403:
@ -42,7 +42,7 @@ class GiphyHandler:
"This is likely due to an invalid key.\n" "This is likely due to an invalid key.\n"
"Follow the instructions in doc.md for setting an API key." "Follow the instructions in doc.md for setting an API key."
) )
raise ConfigValidationError(error_message) raise ConfigValidationError(error_message) from e
def initialize(self, bot_handler: BotHandler) -> None: def initialize(self, bot_handler: BotHandler) -> None:
self.config_info = bot_handler.get_config_info("giphy") self.config_info = bot_handler.get_config_info("giphy")
@ -76,8 +76,8 @@ def get_url_gif_giphy(keyword: str, api_key: str) -> Union[int, str]:
try: try:
gif_url = data.json()["data"]["images"]["original"]["url"] gif_url = data.json()["data"]["images"]["original"]["url"]
except (TypeError, KeyError): # Usually triggered by no result in Giphy. except (TypeError, KeyError) as e: # Usually triggered by no result in Giphy.
raise GiphyNoResultError raise GiphyNoResultError from e
return gif_url return gif_url

View file

@ -114,15 +114,15 @@ class MentionHandler:
try: try:
alert_id = self.get_alert_id(keyword) alert_id = self.get_alert_id(keyword)
except (TypeError, KeyError): except (TypeError, KeyError) as e:
# Usually triggered by invalid token or json parse error when account quote is finished. # Usually triggered by invalid token or json parse error when account quote is finished.
raise MentionNoResponseError raise MentionNoResponseError from e
try: try:
mentions = self.get_mentions(alert_id) mentions = self.get_mentions(alert_id)
except (TypeError, KeyError): except (TypeError, KeyError) as e:
# Usually triggered by no response or json parse error when account quota is finished. # Usually triggered by no response or json parse error when account quota is finished.
raise MentionNoResponseError raise MentionNoResponseError from e
reply = "The most recent mentions of `" + keyword + "` on the web are: \n" reply = "The most recent mentions of `" + keyword + "` on the web are: \n"
for mention in mentions: for mention in mentions:

View file

@ -97,8 +97,8 @@ def get_trivia_payload() -> Dict[str, Any]:
try: try:
data = requests.get(url) data = requests.get(url)
except requests.exceptions.RequestException: except requests.exceptions.RequestException as e:
raise NotAvailableError raise NotAvailableError from e
if data.status_code != 200: if data.status_code != 200:
raise NotAvailableError raise NotAvailableError