4

I'm looking for a way to catch mako runtime errors using Bottle.

Runtime errors in python are catched using the following code:

# main.py
from lib import errors
import bottle

app = bottle.app()
app.error_handler = errors.handler
...

# lib/errors.py
from bottle import mako_template as template

def custom500(error):
    return template('error/500')

handler = {
    500: custom500
}

This works flawlessly, as exceptions are turned into 500 Internal Server Error.

I'd like to catch the mako runtime errors in a similar fashion, does anyone have a clue of how to achieve this?

Andreas
  • 1,211
  • 1
  • 10
  • 21

1 Answers1

3

You want to catch mako.exceptions.SyntaxException.

This code works for me:

@bottle.route('/hello')
def hello():
    try:
        return bottle.mako_template('hello')

    except mako.exceptions.SyntaxException as exx:
        return 'mako exception: {}\n'.format(exx)

EDIT: Per your comment, here are some pointers on how to install this globally. Install a bottle plugin that wraps your functions in the mako.exceptions.SyntaxException try block.

Something along these lines:

@bottle.route('/hello')
def hello():
    return bottle.mako_template('hello')

def catch_mako_errors(callback):
    def wrapper(*args, **kwargs):
        try:
            return callback(*args, **kwargs)
        except mako.exceptions.SyntaxException as exx:
            return 'mako exception: {}\n'.format(exx)
    return wrapper

bottle.install(catch_mako_errors)
ron rothman
  • 17,348
  • 7
  • 41
  • 43
  • Aha, I didn't know you could do that. But what if there are many routes? Do I have to do the same thing on all routes, or can it be performed globally somehow? – Andreas Aug 30 '13 at 17:44
  • If you want to catch them globally, you can install a bottle plugin. I'll update my answer with some references which will point the way. – ron rothman Aug 30 '13 at 18:13
  • Done--I've added code that works globally to my original answer. Did that do the trick? – ron rothman Sep 01 '13 at 17:21
  • Just tried your first suggestion, without success. The second one allows me to catch python exceptions, but not mako. – Andreas Sep 03 '13 at 08:09
  • I found my problem! I've been using `debug=True` when starting bottle. When debug is enabled, mako exceptions are catched within bottle and a custom error page is showed. By removing it, the exception is not handled inside bottle and I can catch it myself. – Andreas Sep 03 '13 at 08:32