Reputation:
I'd like to be able to display custom error messages using abort() in Flask. I have run into an unusual situation that I am having trouble with. My code is below.
from flask import Flask, abort, jsonify, make_response, request
app = Flask(__name__)
@app.errorhandler(400)
def custom400(error):
return make_response(jsonify({'message': error.description}), 400)
@app.route('/test', methods=['POST'])
def test():
abort(400, 'custom error message')
if __name__ == '__main__':
app.run()
The code above works but behaves differently if I attempt to access any form data because I lose access to the custom error message.
def test():
a = request.form['some_value']
abort(400, 'custom error message')
How can I avoid this situation? Is this a Flask bug?
Note: The code above was taken from how to get access to error message from abort command when using custom error handler
Upvotes: 5
Views: 11032
Reputation: 1175
If you want to be able to render a template together with the error message, you can define the error handler
@app.errorhandler(404)
def page_not_found(error):
error=['Page Not Found','Oops']
return render_template('errors.html', error=error), 404
To use, raise the error by
abort(404)
Make sure to import abort
from flask import abort
Then you can access the error message list in jinja
Upvotes: 1
Reputation: 159905
The error doesn't have a description because you aren't setting some_value
in your POST body so the 400 error comes from request.form.__getitem__
- change the first line of test to a = request.form.get('some_value')
and your abort
error will be thrown instead.
Upvotes: 4