2015-07-20 98 views
1

抓住下面的代码捕获Not Found例外:无效的路线不被@ app.errorhandler(异常)在烧瓶

@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()用于不适用于资源的用户。

+0

你在用烧瓶吗? – doru

+0

@doru是它用于处理资源路由的模块。当然,除此之外,我还有其他不使用烧瓶的路线,它使用'@ app.route()' – ALH

+0

尝试Flask的最新开发版本'pip install https://github.com/mitsuhiko/flask/压缩包/ master'的。对于如何处理例外的工作进行了大量的工作。这*可能无法在稳定版本中解决。 – davidism

回答

2

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

但是,您可以在构造函数中添加另一个参数catch_all_404s,其中需要bool

From here

api = Api(app, catch_all_404s=True) 

这应该让你的handle_error()方法404错误路线。

即使这样做后,如果它不以你的方式处理错误,你可以继承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) 

让我知道这是否正常工作。这是我堆栈溢出的第一个答案之一。