tags:

views:

98

answers:

2

How can I send an email to admin when a 500 error occurs, in python.

The web framework I'm using is 'bottle'.

A: 

The following is a line from the Bottle documentation.

All unhandled exceptions other than bottle.HTTPError will result in a 500 Internal Server Error response, so they won't crash your WSGI server.

Judging by this you would want to catch those Exceptions and write the code to send an email to whomsoever it may concern. Your code will go into the try block and you will have a some code for the bottle.HTTPError exception and then code to catch all other Exceptions which sends the desired email.

Ashish
+2  A: 

Just use the @error(code) decorator to define an error handling page, like so:

from bottle import run, error, route

@error(500)
def handle_500_error(code):
  # add mail send code here
  return "Error message here"

@route("/test_500")
def cause_error():
  raise Exception

run()

Just navigate to /test_500 to see it in action

You can of course use a template for the error page just like with any other page. I'm not sure if there's a way to get the built-in bottle error page while having an error handler.

Edit:

Apparently if you're using the latest Bottle v0.8, the function to which you apply the @error decorator receives as a parameter not the error code, but an bottle.HTTPError object, which contains the exception and traceback.

Alternatively, you can set Bottle to not handle exceptions by setting bottle.app().catchall to False as described here, and then use some appropriate WSGI middleware to handle them and send the email (e.g. something like this).

Liquid_Fire
Thanks. Actually I want to know that is there any thing provided by bottle, which we can use to send 500 errors email as provided in django. (In case if I don't want to write the above code)
Tauquir
Actually your suggestion can only email me. I could not get where it went wrong because it will not give any traceback as django gives. So, is there any alternate way?
Tauquir
I think there must be some way to get the exception. I'll have a look.
Liquid_Fire
Here is an "Send e-mail on 500" example: http://paste.pocoo.org/show/243396/
Marcel