Skip to content

Commit

Permalink
Re-raise webhook exceptions
Browse files Browse the repository at this point in the history
So normal Django exception handling sees them.  Resolves dj-stripe#833
  • Loading branch information
therefromhere committed Feb 25, 2019
1 parent 1824214 commit 376ce36
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 5 deletions.
3 changes: 3 additions & 0 deletions djstripe/models/webhooks.py
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,9 @@ def from_request(cls, request):
webhook_processing_error.send(
sender=WebhookEventTrigger, exception=e, data=getattr(e, "http_body", "")
)

# re-raise the exception so Django sees it
raise e
finally:
obj.save()

Expand Down
6 changes: 1 addition & 5 deletions djstripe/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
"""
import logging

from django.http import HttpResponse, HttpResponseBadRequest, HttpResponseServerError
from django.http import HttpResponse, HttpResponseBadRequest
from django.utils.decorators import method_decorator
from django.views.decorators.csrf import csrf_exempt
from django.views.generic import View
Expand Down Expand Up @@ -34,10 +34,6 @@ def post(self, request):

trigger = WebhookEventTrigger.from_request(request)

if trigger.exception:
# An exception happened, return 500
return HttpResponseServerError()

if trigger.is_test_event:
# Since we don't do signature verification, we have to skip trigger.valid
return HttpResponse("Test webhook successfully received!")
Expand Down
23 changes: 23 additions & 0 deletions tests/test_webhooks.py
Original file line number Diff line number Diff line change
Expand Up @@ -156,6 +156,29 @@ def test_webhook_no_remote_addr(self):
event_trigger = WebhookEventTrigger.objects.first()
self.assertEqual(event_trigger.remote_ip, "0.0.0.0")

@patch("djstripe.models.WebhookEventTrigger.validate", return_value=True)
@patch("djstripe.models.WebhookEventTrigger.process")
def test_webhook_reraise_exception(
self, webhook_event_process_mock, webhook_event_validate_mock
):
class ProcessException(Exception):
pass

exception_message = "process fail"

webhook_event_process_mock.side_effect = ProcessException(exception_message)

self.assertEqual(WebhookEventTrigger.objects.count(), 0)

fake_event = deepcopy(FAKE_EVENT_TRANSFER_CREATED)

with self.assertRaisesMessage(ProcessException, exception_message):
self._send_event(fake_event)

self.assertEqual(WebhookEventTrigger.objects.count(), 1)
event_trigger = WebhookEventTrigger.objects.first()
self.assertEqual(event_trigger.exception, exception_message)

@patch.object(
djstripe_settings, "WEBHOOK_EVENT_CALLBACK", return_value=mock_webhook_handler
)
Expand Down

0 comments on commit 376ce36

Please sign in to comment.