views:

77

answers:

2

I'm new to Django and have some code in my views.py like this:

try:
    myfunction()
except:
    assert False, sys.exc_info()[0]

This is very helpful because I get an email with lots of useful info if there's an error. The problem is that it also redirects the user to a Webfaction system error page. What I'd like to know is how do I still get the useful error email, but redirect the user to my own error page?

Also, is this the best way to be handling errors in Django?

A: 

How about using mail_admins to mail yourself when something's up?

eg

from django.template.loaders import render_to_string

...

try:
   #something cool but edgy here
except YourFavouriteException, yfe:
   message_body = render_to_string('path/to/a/template/if/you/want.txt', {'exception': yfe, 'type_of_exception': type(yfe) } ## you could add more detail to this, of course
   mail_admins('Something exploded', message_body)
stevejalim
You could just catch a general Exception here, rather than a particular one
stevejalim
Thanks for your response.
swisstony
You're welcome!
stevejalim
+2  A: 

This is wrong on quite a few levels.

Firstly, there is no reason to catch an exception only to raise another one. If your application raises an exception, then Django's own middleware will catch it, and depending on whether or not you have DEBUG=True, either show a detailed debugging page, or mail the exception to the users mentioned in the ADMINS setting.

Secondly, you should never be getting a Webfaction error page - I can't even imagine how that is happening. If you want your users to see a nice error page, you should define 404.html and 500.html templates, or even full error-handling views if your needs are more complicated. This is fully explained in the documentation.

Daniel Roseman
I've take out the exception catching, added a 500.html template and it's all working fine. The user gets a nice error page and I get an email with the details of the exception. So simple - I'm really liking Django :-) Thanks.
swisstony
No problem. Don't forget to accept the answer if you liked it.
Daniel Roseman