Example – Handling ErrorsΒΆ

It may be desirable to have uniform error-handling code for many routes. We can do this with Klein.handle_errors.

Below we have created a class that will translate NotFound exceptions into a custom 404 response.

from klein import Klein

class NotFound(Exception):

class ItemStore(object):
    app = Klein()

    def notfound(self, request, failure):
        return 'Not found, I say'

    def droid(self, request, name):
        if name in ['R2D2', 'C3P0']:
            raise NotFound()
        return 'Droid found'

    def bounty(self, request, target):
        if target == 'Han Solo':
            return '150,000'
        raise NotFound()

if __name__ == '__main__':
    store = ItemStore()
    store.app.run('localhost', 8080)

The following cURL commands (and output) can be used to test this behaviour:

curl -L http://localhost:8080/droid/R2D2
Not found, I say

curl -L http://localhost:8080/droid/Janeway
Droid found

curl -L http://localhost:8080/bounty/things
Not found, I say