Search code examples
pythonbottle

Emailing admin when a 500 error occurs


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

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


Solution

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