Reputation: 15082
I have a Flask app with a route that looks like this:
from _mysql_exceptions import OperationalError
@mod.route('/', methods=['POST'])
def do_something_route():
try:
do_something(request.form)
except OperationalError:
message = {"error": "something went wrong"}
return jsonify(message, mimetype='application/json'), 400
The do_something()
function:
def do_something(self, form_data):
model = MyModel()
for key in form_data:
if hasattr(model, key):
setattr(model, key, form_data.get(key))
db.session.add(model)
db.session.commit()
return model
When I send garbage data to do_something_route
that violates my DB constraints, an OperationalError
exception is raised and a response with a status code of 500 and the stack trace is returned, not my jsonified message with a status of 400.
When I try this is a plain old python shell, it seems to work as expected:
>>> from _mysql_exceptions import OperationalError
>>> raise OperationalError
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
_mysql_exceptions.OperationalError
>>> try:
... raise OperationalError
... except OperationalError:
... print 'test'
...
test
Why is except OperationalError:
not catching OperationalError
exceptions? Is Flask doing some black magic that is returning a response early?
Upvotes: 2
Views: 5551
Reputation: 1929
from sqlalchemy.exc import OperationalError
try:
# do something
except OperationalError:
# do something
Upvotes: 2