Bottle.py error routing

comamitc picture comamitc · Aug 24, 2011 · Viewed 8.4k times · Source

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

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

however, when importing this statement error is unresolved but on running the application ignores this and just directs me to the generic error page.

I found a way to get around this by:

from bottle import Bottle

main = Bottle()

@Bottle.error(main, 500)
def custom500(error):
    return 'my custom message'

But this code prevents me from embedding my errors all in a separate module to control the nastiness that would ensue if I kept them in my main.py module because the first argument has to be a bottle instance.

So my questions:

  1. Has anyone else experienced this?

  2. why doesn't error seem to resolve in only my case (I installed from pip install bottle)?

  3. Is there a seamless way to import my error routing from a separate python module into the main application?

Answer

zeekay picture zeekay · Aug 24, 2011

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('/')
def divzero():
    return 1/0

run(app)