5

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

Community
  • 1
  • 1
  • Can you clarify what you mean by "I lose access to the custom error message"? – Oin Feb 04 '16 at 19:58
  • 1
    I'm almost certain that 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__` - what happens if you change the first line of `test` to `a = request.form.get('some_value')`? – Sean Vieira Feb 04 '16 at 20:03
  • @SeanVieira - You are right! I had no idea that my attempt to access an invalid dictionary object resulted in a 400. Could you please post your comment as an answer so I can accept it? –  Feb 04 '16 at 20:14

2 Answers2

4

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.

Sean Vieira
  • 155,703
  • 32
  • 311
  • 293
1

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

Patrick Mutuku
  • 1,095
  • 15
  • 13
  • 2
    Those using the stock error mechanisms can simply pass in an additional argument `abort(404,"I don't know what you're up to there but it ain't right")` – Carel Aug 06 '19 at 18:35