【问题标题】:Catch mako runtime errors using Bottle使用 Bottle 捕获 mako 运行时错误
【发布时间】:2013-09-01 12:35:49
【问题描述】:

我正在寻找一种使用 Bottle 捕获 mako 运行时错误的方法。

使用以下代码捕获 Python 中的运行时错误:

# 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
}

这可以完美运行,因为异常会变成 500 Internal Server Error。

我想以类似的方式捕获 mako 运行时错误,有人知道如何实现这一点吗?

【问题讨论】:

    标签: python bottle mako


    【解决方案1】:

    你想抓住mako.exceptions.SyntaxException

    此代码适用于我:

    @bottle.route('/hello')
    def hello():
        try:
            return bottle.mako_template('hello')
    
        except mako.exceptions.SyntaxException as exx:
            return 'mako exception: {}\n'.format(exx)
    

    编辑:根据您的评论,这里有一些关于如何在全球范围内安装它的指示。安装一个 bottle plugin 将你的函数包装在 mako.exceptions.SyntaxException try 块中。

    类似的东西:

    @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)
    

    【讨论】:

    • 啊哈,我不知道你能做到。但是如果有很多路线怎么办?我是否必须在所有路线上做同样的事情,还是可以以某种方式在全球范围内执行?
    • 如果你想全局捕获它们,你可以安装一个瓶子插件。我会用一些可以指明方向的参考资料来更新我的答案。
    • 完成——我已将可在全球范围内使用的代码添加到我的原始答案中。这样做成功了吗?
    • 刚刚尝试了您的第一个建议,但没有成功。第二个允许我捕获 python 异常,但不是 mako。
    • 我发现了我的问题!开始瓶子时我一直在使用debug=True。启用调试后,会在瓶子中捕获 mako 异常并显示自定义错误页面。通过删除它,异常不在瓶子内处理,我可以自己捕捉它。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-18
    • 2012-04-15
    • 2011-02-04
    • 2015-09-29
    相关资源
    最近更新 更多