Signal on management command exception

71 views
Skip to first unread message

Yo-Yo Ma

unread,
May 15, 2020, 11:12:39 AM5/15/20
to Django developers (Contributions to Django itself)
Request exceptions have always been easy to manage, because you can use middleware, and there is the built-in signal: https://docs.djangoproject.com/en/3.0/ref/signals/#got-request-exception

Problem:

However, if you want to send data to e.g., Sentry or perform some other action (logging, etc.) upon any Django management command error, there aren't built-in facilities to deal with this. Even writing your own command base class won't suffice, because that won't cover built-in or third-party commands.

Solution:

I propose a "got_command_exception" signal, which would operate similarly to "got_request_exception", except that it would pass in the management command class instance as the `sender`, and the provided args/kwargs. Being run inside of the exception handler would allow for logging.exception(...) and other exc_info needs.


Due to the fact that all commands run through the same call_command infrastructure, I think this is a good approach to solving the problem I described.

If a majority of folks think this is a good approach, I'll make a patch.

Thoughts?

François Freitag

unread,
May 15, 2020, 11:23:03 AM5/15/20
to django-d...@googlegroups.com
Hi Yo-Yo Ma,

A subset of your use case should be handled by
https://code.djangoproject.com/ticket/21429 -- BaseCommand should use
logging instead of custom output wrappers.

I’m actively working on it and hope to have it ready for Django 3.2. It
allows configuring the reporting of exceptions for built-in management
commands, but I don’t think it is an appropriate way to execute custom
code on command error.

Cheers,
François Freitag

Adam Johnson

unread,
May 15, 2020, 12:46:07 PM5/15/20
to django-d...@googlegroups.com
Yo-Yo Ma,

Typically I've edited manage.py to handle this use case:

def main():
    # ...
    try:
        execute_from_command_line(sys.argv)
    except Exception:
        # whatever
        raise

This doesn't capture programmatic calls via call_command() . But in my experience that's rarely used out side of tests, and one can also write an custom wrapper for call_command().

--
You received this message because you are subscribed to the Google Groups "Django developers  (Contributions to Django itself)" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-develop...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-developers/2020d9ce-e6aa-6a6c-7cfd-851a836a5acc%40gmail.com.


--
Adam
Reply all
Reply to author
Forward
0 new messages