Skip to main content
 首页 » 编程设计

python之flask 中的@app.errorhandler(Exception) 不会捕获无效路由

2024年10月24日34mq0036

下面的代码捕获了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 的 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 的第一个回答。