【问题标题】:Invalid routes are not caught by @app.errorhandler(Exception) in flask无效路由不会被烧瓶中的@app.errorhandler(Exception) 捕获
【发布时间】:2015-10-09 10:38:39
【问题描述】:

以下代码捕获Not Found异常:

@app.errorhandler(404) 
def default_handler(e):
    return 'not-found', 404

问题是当我使用通用errorhandler 时,它无法捕获404 错误:

@app.errorhandler(Exception)
def default_handler(e):
    return 'server-error', 500

目前我使用错误处理程序一个来处理404,另一个处理其他错误。为什么Not Found 异常没有被第二个捕获?有没有办法使用errorhandler

编辑:
路由是flask-restful@app.route() 的句柄。 flask-restful用于处理资源,@app.route()用于不适用资源的处理。

【问题讨论】:

  • 你在用flask-restful吗?
  • @doru 是的,它是我用来处理资源路由的模块。当然除了它我还有其他不使用flask-restful的路线,它使用@app.route()

标签: python exception error-handling flask


【解决方案1】:

我假设您只是将 Flask 的 app 对象传递给 Api 构造函数。

但是,您可以在名为 catch_all_404s 的构造函数中添加另一个参数,该参数采用 bool

From here:

api = Api(app, catch_all_404s=True)

这应该让404 错误路由到您的handle_error() 方法。

即使在这样做之后,如果它不能按照您的方式处理错误,您也可以将 Api 子类化。 From here:

class MyApi(Api):
    def handle_error(self, e):
        """ Overrides the handle_error() method of the Api and adds custom error handling
        :param e: error object
        """
        code = getattr(e, 'code', 500)  # Gets code or defaults to 500
        if code == 404:
            return self.make_response({
                'message': 'not-found',
                'code': 404
            }, 404)
    return super(MyApi, self).handle_error(e)  # handle others the default way

然后在这样做之后,您可以使用MyApi 对象而不是Api 对象来初始化您的api 对象。

这样,

api = MyApi(app, catch_all_404s=True)

让我知道这是否有效。这是我在 Stack Overflow 上的第一个答案。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-02-04
    • 1970-01-01
    • 2022-01-23
    • 1970-01-01
    • 2014-02-14
    • 2020-10-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多