我试图让我的自定义错误处理程序在引发异常时调用。我对python / flask / werkzeug有点新鲜。我用werkzeug DispatcherMiddleware包装我的api,似乎无法调用我的自定义处理程序。
manage.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
答案 0 :(得分:0)
在create_app函数内部,更改:
app.errorhandler(BaseErrorException)(on_error)
app.errorhandler(BaseFormException)(on_formerror)
app.errorhandler(404)(on_404)
by:
if not app.debug:
for e in [500, 404, 403]:
app.errorhandler(e)(handle_error)
function handle_error:
def handle_error(e):
# return render_template('errors/403.html')
# return render_template('errors/404.html')
return render_template('errors/500.html')
希望有所帮助。
答案 1 :(得分:0)
例如
@app.errorhandler(500)
def handle_500(error):
error_msg = util.error_msg()
logger.get("cgi-log").error(error_msg)
if config.debug:
return error
msg = "system error"
return ErrorResponse(msg).output(), 200
@app.errorhandler(Exception)
def handle_exception(error):
error_msg = util.error_msg()
logger.get("cgi-log").error(error_msg)
if config.debug:
return error
msg = "system error"
return ErrorResponse(msg).output(), 200
@app.errorhandler(404)
def page_not_found(error):
return ErrorResponse('Not Found').output(), 404
@app.errorhandler(405)
def method_not_allow(error):
return ErrorResponse(str(error)).output(), 405