下面的代码捕获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()用于不适用于资源的人。
发布于 2015-07-23 16:47:23
我假设您只是将app对象的Api对象传递给Api构造函数。
但是,您可以在构造器中添加另一个参数,称为catch_all_404s,它接受一个bool。
从这里开始
api = Api(app, catch_all_404s=True)这将使404错误路由到您的handle_error()方法。
即使这样做了,如果它不以您的方式处理错误,也可以子类Api。从这里开始
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然后,您可以使用api对象而不是Api对象初始化您的Api对象。
像这样,
api = MyApi(app, catch_all_404s=True)如果这有用的话请告诉我。这是我对堆栈溢出的第一个回答。
https://stackoverflow.com/questions/31514257
复制相似问题