python / expert
Snippet
Capturing and Structuring Exceptions in Custom Signal Handlers
Django's `send_robust` allows signal handlers to fail without interrupting execution, returning exception instances instead of raising them immediately. This helper aggregates those raised exceptions into a single structured report.
snippet.py
python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
from django.dispatch import Signalfrom django.core.exceptions import ValidationErrorimport logginglogger = logging.getLogger(__name__)user_action_signal = Signal()def safe_signal_dispatch(signal, sender, **kwargs):results = signal.send_robust(sender=sender, **kwargs)errors = []for receiver, response in results:if isinstance(response, Exception):logger.error(f'Error in {receiver}: {response}')errors.append((receiver, response))if errors:raise ValidationError(f'Signal dispatch completed with {len(errors)} errors.')return results
django
Breakdown
1
user_action_signal = Signal()
Instantiates a custom Django signal dispatcher instance.
2
results = signal.send_robust(sender=sender, **kwargs)
Executes all registered receivers, catching exceptions per handler and returning pairs of (receiver, response_or_exception).
3
if isinstance(response, Exception):
Inspects each handler result to identify whether an uncaught exception occurred within the signal receiver.