How to catch all exceptions with CherryPy?

I use CherryPy to run a very simple web server. It is designed to process parameters GETand, if they are true, 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

cherrypy.quickstart(MainServer())

For example,

http://127.0.0.1:8080/abcde:

 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 clients do not care about this. In particular, the result will be an empty object, regardless of the url string or query that led to the exception.

I looked at the error handling documentation cherrypy._cperror, but I did not find a way to use it.

EDIT : I gave up using CherryPyand found a simple solution using BaseHTTPServer(see my answer below, downvoted because it solves the problem but doesn't answer the question ... sigh ...)

+4
5

CherryPy IS, . , .

. , , , , , . , , .

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}

    @cherrypy.expose
    def index(self):
        """Root url handler"""

        raise Exception 

. this .

+3

: , .

, BaseHTTPServer. , (, Flask), , , WSGI WSGI- .

+3

try/except:

try:
    cherrypy.quickstart(MainServer())
except: #catches all errors, including basic python errors
    print("Error!")

. cherrypy._cperror:

from cherrypy import _cperror

try:
    cherrypy.quickstart(MainServer())
except _cperror.CherryPyException: #catches only CherryPy errors.
    print("CherryPy error!")

, !

+2

, , . cherrypy 14.0.0

# Implement handler method
def exception_handler(status, message, traceback, version)
    # Your logic goes here 

class MyClass()    

   # Update configurations
   _cp_config = {"error_page.default": exception_handler}

. . ,

  • status : HTTP status and description
  • message : message attached to the exception
  • trace : formatted stack trace
  • version : cherrypy version
0
source

I refused to use CherryPyand ended up using follwing code that solves the problem in a few lines with the standard one BaseHTTPServer:

from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
from urlparse import urlparse, parse_qs

class GetHandler(BaseHTTPRequestHandler):
    def do_GET(self):
        url = urlparse(self.path)
        d = parse_qs(url[4])
        if 'c' in d:
            print d['c'][0]
        self.send_response(200)
        self.end_headers()
        return

server = HTTPServer(('localhost', 8080), GetHandler)
server.serve_forever()
-1
source

All Articles