Zulip server and web application. Open-source team chat that helps teams stay productive and focused.
ruff: Fix TRY401 Redundant exception object included in `logging.exception` call.
Anders Kaseorgcd2aed28235d
diff --git a/corporate/lib/stripe.py b/corporate/lib/stripe.pyindex 18e57b509a7..d8fc75e3124 100644--- a/corporate/lib/stripe.py+++ b/corporate/lib/stripe.py@@ -6012,7 +6012,7 @@ def invoice_plans_as_needed(event_time: datetime | None = None) -> None:stack_info=True,)else:- billing_logger.exception(e, stack_info=True) # nocoverage+ billing_logger.exception("Error while invoicing", stack_info=True) # nocoveragedef is_realm_on_free_trial(realm: Realm) -> bool:diff --git a/puppet/kandra/files/statuspage-pusher b/puppet/kandra/files/statuspage-pusherindex 2869a875f22..3202fb063cc 100755--- a/puppet/kandra/files/statuspage-pusher+++ b/puppet/kandra/files/statuspage-pusher@@ -71,8 +71,8 @@ def main() -> None:for metric_id, query in metrics.items():try:update_metric(metric_id, query, page_id, oauth_token)- except Exception as e:- logging.exception(e)+ except Exception:+ logging.exception("Error while updating metric")time.sleep(30)diff --git a/puppet/zulip/files/postgresql/wal-g-exporter b/puppet/zulip/files/postgresql/wal-g-exporterindex 1aaaf5e5b78..e394b121fce 100755--- a/puppet/zulip/files/postgresql/wal-g-exporter+++ b/puppet/zulip/files/postgresql/wal-g-exporter@@ -141,8 +141,8 @@ class WalGPrometheusServer(BaseHTTPRequestHandler):(t("finish_time") - t("start_time")) / timedelta(seconds=1), labels)backup_ok(1)- except Exception as e:- logging.exception(e)+ except Exception:+ logging.exception("Error while getting backup information")finally:self.print_metrics()self.log_message(diff --git a/zerver/actions/data_import.py b/zerver/actions/data_import.pyindex 75a4ec93e41..7f1ef8157e5 100644--- a/zerver/actions/data_import.py+++ b/zerver/actions/data_import.py@@ -189,7 +189,7 @@ def import_slack_data(event: dict[str, Any]) -> None:preregistration_realm.save()logger.info("(%s) All done!", string_id)except Exception as e:- logger.exception(e)+ logger.exception("Error during Slack import")try:preregistration_realm.created_realm = Nonepreregistration_realm.data_import_metadata["is_import_work_queued"] = Falsediff --git a/zerver/forms.py b/zerver/forms.pyindex 30b8c438236..d2ef200ab3b 100644--- a/zerver/forms.py+++ b/zerver/forms.py@@ -405,8 +405,8 @@ def validate_captcha_payload(request: HttpRequest, captcha_payload: str) -> Noneraise forms.ValidationError(_("Validation failed, please try again."))except forms.ValidationError:raise- except Exception as e:- logging.exception(e)+ except Exception:+ logging.exception("Error while validating altcha solution")raise forms.ValidationError(_("Validation failed, please try again."))captcha_data = orjson.loads(base64.b64decode(captcha_payload))diff --git a/zerver/lib/cache.py b/zerver/lib/cache.pyindex 6ab1b604d20..6d2ad85f207 100644--- a/zerver/lib/cache.py+++ b/zerver/lib/cache.py@@ -251,8 +251,8 @@ def cache_set(val = (val,)try:cache_backend.set(final_key, val, timeout=timeout)- except MemcachedException as e:- logger.exception(e)+ except MemcachedException:+ logger.exception("Error while storing to cache")remote_cache_stats_finish()@@ -306,8 +306,8 @@ def cache_set_many(remote_cache_stats_start()try:get_cache_backend(cache_name).set_many(items, timeout=timeout)- except MemcachedException as e:- logger.exception(e)+ except MemcachedException:+ logger.exception("Error while storing to cache")remote_cache_stats_finish()diff --git a/zerver/lib/email_mirror_server.py b/zerver/lib/email_mirror_server.pyindex 512d3465b45..763293f0194 100644--- a/zerver/lib/email_mirror_server.py+++ b/zerver/lib/email_mirror_server.py@@ -64,8 +64,8 @@ def send_to_postmaster(msg: email.message.Message) -> None:e.smtp_error,stack_info=True,)- except smtplib.SMTPException as e:- logger.exception("Error sending bounce email to %s: %s", mail.to, str(e), stack_info=True)+ except smtplib.SMTPException:+ logger.exception("Error sending bounce email to %s", mail.to, stack_info=True)class ZulipMessageHandler(MessageHandler):diff --git a/zerver/lib/send_email.py b/zerver/lib/send_email.pyindex e3f013338ba..ee85b5a514d 100644--- a/zerver/lib/send_email.py+++ b/zerver/lib/send_email.py@@ -352,7 +352,7 @@ def send_immediate_email(connection.close()raise EmailNotDeliveredError from eexcept (smtplib.SMTPException, OSError) as e:- logger.exception("Error sending %s email to %s: %s", template, mail.to, e, stack_info=True)+ logger.exception("Error sending %s email to %s", template, mail.to, stack_info=True)connection.close()raise EmailNotDeliveredError from ediff --git a/zerver/lib/thumbnail.py b/zerver/lib/thumbnail.pyindex 67e65136420..ff2867c7ac0 100644--- a/zerver/lib/thumbnail.py+++ b/zerver/lib/thumbnail.py@@ -194,8 +194,8 @@ def libvips_check_image(try:yield source_image- except pyvips.Error as e: # nocoverage- logging.exception(e)+ except pyvips.Error: # nocoverage+ logging.exception("Error while processing image")raise BadImageError(_("Image is corrupted or truncated"))diff --git a/zerver/lib/zulip_update_announcements.py b/zerver/lib/zulip_update_announcements.pyindex 97a90a78d73..4bb3c122823 100644--- a/zerver/lib/zulip_update_announcements.py+++ b/zerver/lib/zulip_update_announcements.py@@ -809,8 +809,8 @@ def send_zulip_update_announcements(skip_delay: bool, progress: bool = False) ->for i, realm in enumerate(realms, start=1):try:send_zulip_update_announcements_to_realm(realm, skip_delay)- except Exception as e: # nocoverage- logging.exception(e)+ except Exception: # nocoverage+ logging.exception("Error while sending update announcements")finally:if progress and i % 50 == 0: # nocoverageprint(f"Processed {i}/{len(realms)} realms...")diff --git a/zerver/middleware.py b/zerver/middleware.pyindex 217108eed4d..c23cac63cb7 100644--- a/zerver/middleware.py+++ b/zerver/middleware.py@@ -299,8 +299,8 @@ class LogRequests(MiddlewareMixin):try:request_notes.client_name, request_notes.client_version = parse_client(request)- except JsonableError as e:- logging.exception(e)+ except JsonableError:+ logging.exception("Error while parsing client from request")request_notes.client_name = "Unparsable"request_notes.client_version = Nonediff --git a/zerver/tests/test_email_mirror.py b/zerver/tests/test_email_mirror.pyindex cd2555b46fd..efc0f3f35aa 100644--- a/zerver/tests/test_email_mirror.py+++ b/zerver/tests/test_email_mirror.py@@ -2107,11 +2107,14 @@ class TestEmailMirrorServer(ZulipTestCase):self.assertLogs("zerver.lib.email_mirror", "ERROR") as error_log,):send_to_postmaster(email)- self.assert_length(error_log.output, 1)+ self.assert_length(error_log.records, 1)+ self.assertEqual(error_log.records[0].levelname, "ERROR")self.assertEqual(- error_log.output[0].splitlines()[0],- "ERROR:zerver.lib.email_mirror:Error sending bounce email to ['[email protected]']: moose",+ error_log.records[0].getMessage(),+ "Error sending bounce email to ['[email protected]']",)+ assert error_log.records[0].exc_info is not None+ self.assertEqual(str(error_log.records[0].exc_info[1]), "moose")with (mock.patch.object(diff --git a/zerver/tests/test_send_email.py b/zerver/tests/test_send_email.pyindex 6f1292d37b2..659ffbf90a6 100644--- a/zerver/tests/test_send_email.py+++ b/zerver/tests/test_send_email.py@@ -411,18 +411,22 @@ class TestSendEmail(ZulipTestCase):self.assertEqual(mail.extra_headers["From"], f"{from_name} <{FromAddress.NOREPLY}>")# We test the cases that should raise an EmailNotDeliveredError- errors = {- f"Unknown error sending password_reset email to {mail.to}": [0],- f"Error sending password_reset email to {mail.to}": [SMTPException()],- f"Error sending password_reset email to {mail.to}: {{'{address}': (550, b'User unknown')}}": [- SMTPRecipientsRefused(recipients={address: (550, b"User unknown")})- ],- f"Error sending password_reset email to {mail.to} with error code 242: From field too long": [- SMTPDataError(242, "From field too long.")- ],- }+ errors = [+ (f"Unknown error sending password_reset email to {mail.to}", None, [0]),+ (f"Error sending password_reset email to {mail.to}", "", [SMTPException()]),+ (+ f"Error sending password_reset email to {mail.to}",+ f"{{{address!r}: (550, b'User unknown')}}",+ [SMTPRecipientsRefused(recipients={address: (550, b"User unknown")})],+ ),+ (+ f"Error sending password_reset email to {mail.to} with error code 242: From field too long.",+ "(242, 'From field too long.')",+ [SMTPDataError(242, "From field too long.")],+ ),+ ]- for message, side_effect in errors.items():+ for message, exc_message, side_effect in errors:with mock.patch.object(EmailBackend, "send_messages", side_effect=side_effect):with (self.assertLogs(logger=logger) as info_log,@@ -436,11 +440,16 @@ class TestSendEmail(ZulipTestCase):language="en",)self.assert_length(info_log.records, 2)+ self.assertEqual(info_log.records[0].levelname, "INFO")+ self.assertEqual(+ info_log.records[0].getMessage(), f"Sending password_reset email to {mail.to}"+ )+ self.assertEqual(info_log.records[1].levelname, "ERROR")+ self.assertEqual(info_log.records[1].getMessage(), message)self.assertEqual(- info_log.output[0],- f"INFO:{logger.name}:Sending password_reset email to {mail.to}",+ info_log.records[1].exc_info and str(info_log.records[1].exc_info[1]),+ exc_message,)- self.assertTrue(info_log.output[1].startswith(f"ERROR:zulip.send_email:{message}"))def test_send_email_config_error_logging(self) -> None:hamlet = self.example_user("hamlet")diff --git a/zerver/views/antispam.py b/zerver/views/antispam.pyindex aafc41123da..89c4117f703 100644--- a/zerver/views/antispam.py+++ b/zerver/views/antispam.py@@ -48,6 +48,6 @@ def get_challenge((challenge.challenge, expires.timestamp()),]return json_success(request, data=challenge.__dict__)- except Exception as e: # nocoverage- logging.exception(e)+ except Exception: # nocoverage+ logging.exception("Error while generating challenge")raise JsonableError(_("Failed to generate challenge"))diff --git a/zerver/views/sentry.py b/zerver/views/sentry.pyindex 2310ee28ce5..f711a448230 100644--- a/zerver/views/sentry.py+++ b/zerver/views/sentry.py@@ -87,9 +87,9 @@ def sentry_tunnel(sentry_request(url, updated_body)except CircuitBreakerError:logger.warning("Dropped a client exception due to circuit-breaking")- except RequestException as e:+ except RequestException:# This logger has been configured, above, to not report to Sentry- logger.exception(e)+ logger.exception("Error while reporting to Sentry")return HttpResponse(status=200)