【问题标题】:Errorhandler is not called for custom exception自定义异常不调用错误处理程序
【发布时间】:2019-03-22 23:31:01
【问题描述】:

我有以下错误处理程序:

@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,它就会失败,我会从烧瓶中得到一个 500 模板。

真正有趣的是,之前实现的 ValidationException 运行良好。

我详细了解了发生了什么,当引发 ValidationException 时,它会通过 response.py 并最终进入错误处理程序。不幸的是,我无法理解烧瓶深处发生的一切,但在调试中,DatabaseException 肯定走的是不同的路线。

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

【问题讨论】:

    标签: python flask flask-restful


    【解决方案1】:

    对不起,我的回答有点奇怪。如果你想返回一个 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。

    【讨论】:

      【解决方案2】:

      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)
      

      玩得开心!

      【讨论】:

      • 是的,我想我没有看到那个明显的错误。今天早上我也注意到了。我也无法读取调试器(这有点含糊,为我辩护),如果异常失败或在错误处理程序返回时失败,则无法确定。
      猜你喜欢
      • 1970-01-01
      • 2020-09-26
      • 1970-01-01
      • 2014-05-28
      • 2016-02-02
      • 1970-01-01
      • 2019-08-28
      • 1970-01-01
      • 2011-07-13
      相关资源
      最近更新 更多