我有以下错误处理程序:
@api.errorhandler(DatabaseException)
def handle_database_exception(database_error):
return database_error.query_error, 400
@api.errorhandler(ValidationException)
def handle_validation_exception(validation_error):
return {'fields': validation_error.body_error}, 400
这些是简单的类:
class ValidationException(Exception):
def __init__(self, body_error=None, missing_files=None):
Exception.__init__(self, "Validation failed")
self.body_error = body_error
if missing_files is not None:
for missing_file in missing_files:
self.body_error[missing_file] = ['required file']
class DatabaseException(Exception):
def __init__(self, details):
Exception.__init__(self, "Database Error")
self.query_error = details
这是我的问题: 如果我在任何一条路由中都引发了DatabaseException,它将失败,并且从flask中获得了500个模板。
真正有趣的是,早先实现的ValidationException效果很好。
我详细介绍了发生的情况,当ValidationException引发时,它通过response.py并最终出现在错误处理程序中。不幸的是,我无法理解烧瓶内部深处的所有情况,但是在调试中,DatabaseException肯定是走了另一条路。
我希望错误处理程序被调用。如果在其中一条路由中引发了DatabaseException,则应调用它。
答案 0 :(得分:2)
对不起,我的回答有点奇怪。如果要返回JSON响应,可以这样进行。
class ValidationException(Exception):
def __init__(self, body_error=None, missing_files=None):
Exception.__init__(self, "Validation failed")
self.body_error = body_error
if missing_files is not None:
for missing_file in missing_files:
self.body_error[missing_file] = ['required file']
@api.errorhandler(ValidationException)
def handle_validation_exception(validation_error):
from flask import jsonify, make_response
return make_response(jsonify({'fields': validation_error.body_error}), 400)
这也是可行的。
@api.errorhandler(ValidationException)
def handle_validation_exception(validation_error):
return "{'fields': validation_error.body_error}", 400
DatabaseException可以正常工作,并以纯文本主体返回400 Bad Request。
玩得开心^ 2。
答案 1 :(得分:1)
DatabaseException非常适合我。
在第二种解决方案中,您尝试返回Python字典。我认为缺少引号会导致错误。也许您可以使用jsonify和make_response。
@api.errorhandler(DatabaseException)
def handle_validation_exception(validation_error):
from flask import jsonify, make_response
return make_response(jsonify({ 'fields': validation_error.query_error }), 400)
玩得开心!