Search code examples
pythonexceptionoutputcherrypy

Python 2.* / Cherrypy - Get handled exception as object or string and output to error page


I have an issue with the CherryPy usage and all investigation has not lead to a working solution so far.

I would like to handle and display in a custom page all server errors (Errors with status 500). For example if there is a specific database error, I'd like to display it to the user and give also the string of the Exception.

To generate the error page I am currently using:

_cp_config = {'error_page.500': '<path_to_html_file>'}

But I cannot find out how to catch and pass the exception string and eventually add it to the output to the user.

Note that there are couple of services for communication between the front end and the back end so I'd like to avoid the "try except" structure.

Any advice on how to do it will be useful.

Thanks a lot.

Regards, Teddy


Solution

  • The config options for the error handling can be configured to accept a callable with the following signature: (status, message='', traceback='', version='')

    You could define:

    def error_404(status, message='', traceback='', version=''):
        # do something, like rendering a template or send an email
        return "Not Found" # or return your rendered template
    
    def error_500(status, message='', traceback='', version=''):
        # do something, like rendering a template or send an email
        return "Error 500" # or return your rendered template
    
    _cp_config = {
       'error_page.500': error_500,
       'error_page.404': error_404
     }