[Django]-'AssertionError' object has no attribute 'message'

4👍

The exception object e does not per se has a message attribute. You can for example retrieve it if there is such attribute, and use the empty string if there is no such attribute with getattr(…) [python-doc]:

def send_manually_exception_email(request, e):
  exc_info = sys.exc_info()
  reporter = ExceptionReporter(request, is_email=True, *exc_info)
  subject = getattr(e, 'message', '').replace('\n', '\\n').replace('\r', '\\r')[:989]
  message = "%s\n\n%s" % (
    '\n'.join(traceback.format_exception(*exc_info)),
    reporter.filter.get_request_repr(request)
  )
  mail.mail_admins(subject, message, fail_silently=True, html_message=reporter.get_traceback_html())

7👍

Although better than crashing, OP probably doesn’t want to generate an email with a blank subject line. You can just use the string representation of the error, eg:

print(e)
print(f'Function x gave error {e}')

In OP’s code, it may be good enough to set:

subject = str(e)

Or use this as an alternative if the error does not have a message:

subject = getattr(e, 'message', str(e)).replace('\n', '\\n').replace('\r', '\\r')[:989]

Leave a comment