我试图让我的自定义错误处理程序在引发异常时调用。我对 python/flask/werkzeug 有点陌生。我正在用 werkzeug DispatcherMiddleware 包装我的 api,并且似乎无法调用我的自定义处理程序。
管理.py
from werkzeug.serving import run_simple
from werkzeug.wsgi import DispatcherMiddleware
from myapp import api, web
app = DispatcherMiddleware(web.create_app(), {
'/api': api.create_app()
})
if __name__ == '__main__':
run_simple('0.0.0.0', 5000, app, use_reloader=True, use_debugger=True)
api/初始化.py
def create_app(settings_override=None):
app = Flask(__name__)
api = Api(app)
# Set default encoder
app.json_encoder = JSONEncoder
# Register custom error handlers
app.errorhandler(BaseErrorException)(on_error)
app.errorhandler(BaseFormException)(on_formerror)
app.errorhandler(404)(on_404)
db.init_app(app)
api_urls(api)
return app
def on_error(e):
print 'on_error'
return jsonify(dict(error=e.msg)), 400
def on_formerror(e):
print 'on_formerror'
return jsonify(dict(errors=e.errors)), 400
def on_404(e):
print 'on_404'
return jsonify(dict(error='Not found')), 404
但我不断得到:
{
"status": 500,
"message": "Internal Server Error"
}
控制台输出:
Traceback (most recent call last):
...
raise BaseFormException(form.errors)
BaseFormException