不为自定义异常调用 Errorhandler

Errorhandler is not called for custom exception

我有以下错误处理程序:

@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

这是我的问题: 如果我在我的任何路由中调用 raise DatabaseException,它就会失败,我会从 flask 中获得一个 500 模板。

真正有趣的是,之前实现的 ValidationException 工作得很好。

我详细了解了发生的事情,当 ValidationException 被引发时,它会经过 response.py 并在错误处理程序中结束。不幸的是,我无法理解烧瓶深处发生的一切,但在调试中,DatabaseException 肯定走上了不同的路线。

我希望调用错误处理程序。如果我在其中一条路线中引发 DatabaseException,它应该被调用。

DatabaseException 非常适合我。

在第二个解决方案中,您尝试 return 一个 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)

玩得开心!

抱歉,我的回答有点奇怪。如果你想 return 一个 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 工作正常,returns 400 Bad Request with a plaintext body。

玩得开心^2。