Skip to content Skip to sidebar Skip to footer

Bottle.py Error Routing

Bottle.py ships with an import to handle throwing HTTPErrors and route to a function. Firstly, the documentation claims I can (and so do several examples): from bottle import error

Solution 1:

If you want to embed your errors in another module, you could do something like this:

error.py

def custom500(error):
    return 'my custom message'

handler = {
    500: custom500,
}

app.py

from bottle import *
import error

app = Bottle()
app.error_handler = error.handler

@app.route('/')defdivzero():
    return1/0

run(app)

Solution 2:

In some cases I find it's better to subclass Bottle. Here's an example of doing that and adding a custom error handler.

#!/usr/bin/env python3from bottle import Bottle, response, Route

classMyBottle(Bottle):
    def__init__(self, *args, **kwargs):
        Bottle.__init__(self, *args, **kwargs)
        self.error_handler[404] = self.four04
        self.add_route(Route(self, "/helloworld", "GET", self.helloworld))
    defhelloworld(self):
        response.content_type = "text/plain"yield"Hello, world."deffour04(self, httperror):
        response.content_type = "text/plain"yield"You're 404."if __name__ == '__main__':
    mybottle = MyBottle()
    mybottle.run(host='localhost', port=8080, quiet=True, debug=True)

Post a Comment for "Bottle.py Error Routing"