[英]Catch mako runtime errors using Bottle
我正在尋找一種方法來使用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內部服務器錯誤。
我想以類似的方式捕獲mako運行時錯誤,有沒有人知道如何實現這一點?
您想要捕獲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)
編輯:根據您的評論,這里有一些關於如何全局安裝它的指針。 安裝一個瓶子插件 ,將你的函數包裝在mako.exceptions.SyntaxException嘗試塊中。
這些方面的東西:
@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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.