How to catch all exceptions with CherryPy?

2024/9/8 10:30:12

I use CherryPy to run a very simple web server. It is intended to process the GET parameters and, if they are correct, do something with them.

import cherrypyclass MainServer(object):def index(self, **params):# do things with correct parametersif 'a' in params:print params['a']index.exposed = Truecherrypy.quickstart(MainServer())

For example,

http://127.0.0.1:8080/abcde:404 Not FoundThe path '/abcde' was not found.Traceback (most recent call last):File "C:\Python27\lib\site-packages\cherrypy\_cprequest.py", line 656, in respondresponse.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 cherrypy._cperror, but I did not find a way to actually use it.

Note: I gave up using CherryPy and found a simple solution using BaseHTTPServer (see my answer below)

Answer

Docs somehow seem to miss this section. This is what I found while looking for detailed explanation for custom error handling from the source code.

Custom Error Handling

Anticipated HTTP responses

The 'error_page' config namespace can be used to provide custom HTML output for expected responses (like 404 Not Found). Supply a filename from which the output will be read. The contents will be interpolated with the values %(status)s, %(message)s, %(traceback)s, and %(version)s using plain old Python string formatting.

_cp_config = {'error_page.404': os.path.join(localDir, "static/index.html")
}

Beginning in version 3.1, you may also provide a function or other callable as an error_page entry. It will be passed the same status, message, traceback and version arguments that are interpolated into templates

def error_page_402(status, message, traceback, version):return "Error %s - Well, I'm very sorry but you haven't paid!" % status
cherrypy.config.update({'error_page.402': error_page_402})

Also in 3.1, in addition to the numbered error codes, you may also supply error_page.default to handle all codes which do not have their own error_page entry.

Unanticipated errors

CherryPy also has a generic error handling mechanism: whenever an unanticipated error occurs in your code, it will call Request.error_response to set the response status, headers, and body. By default, this is the same output as HTTPError(500). If you want to provide some other behavior, you generally replace "request.error_response".

Here is some sample code that shows how to display a custom error message and send an e-mail containing the error

from cherrypy import _cperrordef handle_error():cherrypy.response.status = 500cherrypy.response.body = ["<html><body>Sorry, an error occurred</body></html>"]sendMail('[email protected]','Error in your web app',_cperror.format_exc())@cherrypy.config(**{'request.error_response': handle_error})
class Root:pass

Note that you have to explicitly set response.body and not simply return an error message as a result.

https://en.xdnf.cn/q/73014.html

Related Q&A

matplotlib: How can you specify colour levels in a 2D historgram

I would like to plot a 2D histogram that includes both positive and negative numbers. I have the following code which uses pcolormesh but I am unable to specify the color levels to force the white col…

Strange behavior from HTTP authentication with suds SOAP library

I have a working python program that is fetching a large volume of data via SOAP using suds. The web service is implemented with a paging function such that I can grab nnn rows with each fetch call an…

Scipy/Numpy/scikits - calculating precision/recall scores based on two arrays

I fit a Logistic Regression Model and train the model based on training dataset using the following import scikits as sklearn from sklearn.linear_model import LogisticRegression lr = LogisticRegression…

Cant create test client during unit test of Flask app

I am trying to find out how to run a test on a function which grabs a variable value from session[user_id]. This is the specific test method:def test_myProfile_page(self):with app.test_client() as c:w…

My python installation is broken/corrupted. How do I fix it?

I followed these instructions on my RedHat Linux version 7 server (which originally just had Python 2.6.x installed):beginning of instructions install build toolssudo yum install make automake gcc gcc-…

Function that returns a tuple gives TypeError: NoneType object is not iterable

What does this error mean? Im trying to make a function that returns a tuple. Im sure im doing all wrong. Any help is appreciated.from random import randint A = randint(1,3) B = randint(1,3) def make_…

Error when plotting DataFrame containing NaN with Pandas 0.12.0 and Matplotlib 1.3.1 on Python 3.3.2

First of all, this question is not the same as this one.The problem Im having is that when I try to plot a DataFrame which contains a numpy NaN in one cell, I get an error:C:\>\Python33x86\python.ex…

Java method which can provide the same output as Python method for HMAC-SHA256 in Hex

I am now trying to encode the string using HMAC-SHA256 using Java. The encoded string required to match another set of encoded string generated by Python using hmac.new(mySecret, myPolicy, hashlib.sha2…

How to get response from scrapy.Request without callback?

I want to send a request and wait for a response from the server in order to perform action-dependent actions. I write the followingresp = yield scrapy.Request(*kwargs)and got None in resp. In document…

install error thinks pythonpath is empty

I am trying to install the scikits.nufft package here I download the zip file, unpack and cd to the directory. It contains a setup.py file so I run python setup.py installbut it gives me the following …