Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Emailing admin when a 500 error occurs

Tags:

python

bottle

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

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

like image 798
Tauquir Avatar asked Jan 21 '23 17:01

Tauquir


2 Answers

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).

like image 192
Liquid_Fire Avatar answered Feb 02 '23 21:02

Liquid_Fire


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.

like image 29
Jungle Hunter Avatar answered Feb 02 '23 22:02

Jungle Hunter