how to get access to error message from abort command when using custom error handler

richmb picture richmb · Jan 22, 2014 · Viewed 37.5k times · Source

Using a python flask server, I want to be able to throw an http error response with the abort command and use a custom response string and a custom message in the body

@app.errorhandler(400)
def custom400(error):
    response = jsonify({'message': error.message})
    response.status_code = 404
    response.status = 'error.Bad Request'
    return response

abort(400,'{"message":"custom error message to appear in body"}')

But the error.message variable comes up as an empty string. I can't seem to find documentation on how to get access to the second variable of the abort function with a custom error handler

Answer

Sean Vieira picture Sean Vieira · Jan 23, 2014

If you look at flask/__init__.py you will see that abort is actually imported from werkzeug.exceptions. Looking at the Aborter class, we can see that when called with a numeric code, the particular HTTPException subclass is looked up and called with all of the arguments provided to the Aborter instance. Looking at HTTPException, paying particular attention to lines 85-89 we can see that the second argument passed to HTTPException.__init__ is stored in the description property, as @dirn pointed out.

You can either access the message from the description property:

@app.errorhandler(400)
def custom400(error):
    response = jsonify({'message': error.description['message']})
    # etc.

abort(400, {'message': 'custom error message to appear in body'})

or just pass the description in by itself:

@app.errorhandler(400)
def custom400(error):
    response = jsonify({'message': error.description})
    # etc.

abort(400, 'custom error message to appear in body')