WoJ WoJ - 1 month ago 8x
Python Question

How to catch all exceptions with CherryPy?

I use CherryPy to run a very simple web server. It is intended to process the

parameters and, if they are correct, do something with them.

import cherrypy

class MainServer(object):
def index(self, **params):
# do things with correct parameters
if 'a' in params:
print params['a']

index.exposed = True


For example,

404 Not Found

The path '/abcde' was not found.

Traceback (most recent call last):
File "C:\Python27\lib\site-packages\cherrypy\_cprequest.py", line 656, in respond
response.body = self.handler()
File "C:\Python27\lib\site-packages\cherrypy\lib\encoding.py", line 188, in __call__
self.body = self.oldhandler(*args, **kwargs)
File "C:\Python27\lib\site-packages\cherrypy\_cperror.py", line 386, in __call__
raise self
NotFound: (404, "The path '/abcde' was not found.")
Powered by CherryPy 3.2.4

I am trying to catch this exception and show a blank page because the clients do not care about it. Specifically, the result would be an empty body, no matter the url or query string that resulted in an exception.

I had a look at documentation on error handling
, but I did not find a way to actually use it.

EDIT: I gave up using
and found a simple solution using
(see my answer below, downvoted because it solves the issue but does not answer the question ...sigh...)


CherryPy IS catching your exception. That's how it returns a valid page to the browser with the caught exception.

I suggest you read through all the documentation. I realize it isn't the best documentation or organized well, but if you at least skim through it the framework will make more sense. It is a small framework, but does almost everything you'd expect from a application server.

import cherrypy

def show_blank_page_on_error():
    """Instead of showing something useful to developers but
    disturbing to clients we will show a blank page.

    cherrypy.response.status = 500

    cherrypy.response.body = ''

class Root():
    """Root of the application"""

    _cp_config = {'request.error_response': show_blank_page_on_error}

    def index(self):
        """Root url handler"""

        raise Exception 

See this for the example in the documentation on the page mentioned above for further reference.