When i want to use the flask abort inside a try block i end up in my exception block
@app.route('/newsletters/<int:newsletter_id>', methods=['GET'])
def route_get_newsletter(newsletter_id):
if request.method == 'GET':
try:
newsletter = get_newsletter(newsletter_id)
if not newsletter:
abort(404)
except Exception, ex:
logging.exception("Something awful happened!")
abort(500)
else:
return jsonify(newsletter=newsletter)
gives output:
ERROR:root:Something awful happened!
Traceback (most recent call last):
File "natuurpuntapi.py", line 210, in route_get_newsletter
abort(404)
File "/usr/lib/python2.7/dist-packages/werkzeug/exceptions.py", line 525, in __call__
raise self.mapping[code](*args, **kwargs)
NotFound: 404: Not Found
and werkzeug NotFound is called and i get the 500 response
when i put the abort(404) outside the try: block, it works and i get the 404 response
i found that flask abort() uses the werkzeug abort() which is a class called Aborter() when this is called it raises "raise self.mapping[code](*args, **kwargs)"
does this mean i can not call abort inside my own try block because it will raise an exception and ends up in my exception?
flask.abort(...)
raises itself an exception, one of the exceptions described in the docs, all subclasses of werkzeug.exceptions.HTTPException
. This is the reason why your code doesn't work.
But here is some other trivia:
methods=['GET']
, you don't need to check for the method inside the view.Given that knowledge we can rewrite your code like:
@app.route('/newsletters/<int:newsletter_id>', methods=['GET'])
def route_get_newsletter(newsletter_id):
newsletter = get_newsletter(newsletter_id)
return jsonify(newsletter=newsletter)
@app.errorhandler(500)
def catch_server_errors(e):
logging.exception("Something awful happened!")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With