From 2afeba6b1c2eb4d950a4035a2a07933f808992b9 Mon Sep 17 00:00:00 2001 From: Vincent Tang <68221513+vinceta@users.noreply.github.com> Date: Mon, 13 Nov 2023 19:56:52 +1100 Subject: [PATCH] Fix #1421 Update SlackApiError exception handling for web client (#1423) * Update exception handling for SlackApiError * Correct lint error for import --- README.md | 3 +++ slack_sdk/web/base_client.py | 4 ++-- tests/slack_sdk/web/test_web_client.py | 2 +- .../web/test_web_client_http_retry_server_error.py | 11 ++++++++++- tests/slack_sdk/web/test_web_client_issue_829.py | 11 ++++++++++- 5 files changed, 26 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index 5da440626..03a48d169 100644 --- a/README.md +++ b/README.md @@ -107,6 +107,9 @@ except SlackApiError as e: assert e.response["ok"] is False assert e.response["error"] # str like 'invalid_auth', 'channel_not_found' print(f"Got an error: {e.response['error']}") + # Also receive a corresponding status_code + assert isinstance(e.response.status_code, int) + print(f"Received a response status_code: {e.response.status_code}") ``` Here we also ensure that the response back from Slack is a successful one and that the message is the one we sent by using the `assert` statement. diff --git a/slack_sdk/web/base_client.py b/slack_sdk/web/base_client.py index 7dc562444..5bef28764 100644 --- a/slack_sdk/web/base_client.py +++ b/slack_sdk/web/base_client.py @@ -19,7 +19,6 @@ from urllib.parse import urlencode from urllib.request import Request, urlopen, OpenerDirector, ProxyHandler, HTTPSHandler -import slack_sdk.errors as err from slack_sdk.errors import SlackRequestError from .deprecation import show_deprecation_warning_if_any from .internal_utils import ( @@ -299,7 +298,8 @@ def convert_params(values: dict) -> dict: response_body_data = json.loads(response["body"]) except json.decoder.JSONDecodeError: message = _build_unexpected_body_error_message(response.get("body", "")) - raise err.SlackApiError(message, response) + self._logger.error(f"Failed to decode Slack API response: {message}") + response_body_data = {"ok": False, "error": message} all_params: Dict[str, Any] = copy.copy(body_params) if body_params is not None else {} if query_params: diff --git a/tests/slack_sdk/web/test_web_client.py b/tests/slack_sdk/web/test_web_client.py index 46810dea6..024915a20 100644 --- a/tests/slack_sdk/web/test_web_client.py +++ b/tests/slack_sdk/web/test_web_client.py @@ -150,7 +150,7 @@ def test_html_response_body_issue_718(self): self.fail("SlackApiError expected here") except err.SlackApiError as e: self.assertTrue( - str(e).startswith("Received a response in a non-JSON format: