From 2a7d963f509ea1b267bfff9bb494046b99601041 Mon Sep 17 00:00:00 2001 From: lebaudantoine Date: Tue, 27 May 2025 13:39:08 +0200 Subject: [PATCH] =?UTF-8?q?=F0=9F=A5=85(backend)=20catch=20request=20timeo?= =?UTF-8?q?ut=20and=20Brevo=20contact=20addition=20errors?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Handle unhandled exceptions to prevent UX impact. Marketing email operations are optional and should not disrupt core functionality. My first implementation was imperfect, raising error in sentry. --- src/backend/core/services/marketing.py | 3 ++- .../core/tests/services/test_marketing.py | 25 +++++++++++++++++++ 2 files changed, 27 insertions(+), 1 deletion(-) diff --git a/src/backend/core/services/marketing.py b/src/backend/core/services/marketing.py index a8c8fc8f..27243a3f 100644 --- a/src/backend/core/services/marketing.py +++ b/src/backend/core/services/marketing.py @@ -10,6 +10,7 @@ from django.core.exceptions import ImproperlyConfigured from django.utils.module_loading import import_string import brevo_python +import requests logger = logging.getLogger(__name__) @@ -120,7 +121,7 @@ class BrevoMarketingService: try: response = contact_api.create_contact(contact, **api_configurations) - except brevo_python.rest.ApiException as err: + except (brevo_python.rest.ApiException, requests.exceptions.ReadTimeout) as err: logger.exception("Failed to create contact in Brevo") raise ContactCreationError("Failed to create contact in Brevo") from err diff --git a/src/backend/core/tests/services/test_marketing.py b/src/backend/core/tests/services/test_marketing.py index 6a19c70d..ac1b31a4 100644 --- a/src/backend/core/tests/services/test_marketing.py +++ b/src/backend/core/tests/services/test_marketing.py @@ -11,6 +11,7 @@ from django.core.exceptions import ImproperlyConfigured import brevo_python import pytest +import requests from core.services.marketing import ( BrevoMarketingService, @@ -133,6 +134,30 @@ def test_create_contact_api_error(mock_contact_api): brevo_service.create_contact(valid_contact_data) +@mock.patch("brevo_python.ContactsApi") +def test_create_contact_timeout_error(mock_contact_api): + """Test contact creation timeout error handling.""" + + mock_api = mock_contact_api.return_value + settings.BREVO_API_KEY = "test-api-key" + settings.BREVO_API_CONTACT_LIST_IDS = [1, 2, 3, 4] + settings.BREVO_API_CONTACT_ATTRIBUTES = {"source": "test"} + + valid_contact_data = ContactData( + email="test@example.com", + attributes={"first_name": "Test"}, + list_ids=[1, 2], + update_enabled=True, + ) + + brevo_service = BrevoMarketingService() + + mock_api.create_contact.side_effect = requests.exceptions.ReadTimeout() + + with pytest.raises(ContactCreationError, match="Failed to create contact in Brevo"): + brevo_service.create_contact(valid_contact_data) + + @pytest.fixture def clear_marketing_cache(): """Clear marketing service cache between tests."""