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
People rely on
abort()
too much. The truth is that there are much better ways to handle errors.For example, you can write this helper function:
Then from your view function you can return an error with:
If the error occurs deeper in your call stack in a place where returning a response isn't possible then you can use a custom exception. For example:
Then in the function that needs to issue the error you just raise the exception:
I hope this helps.
flask.abort also accepts flask.Response
If you look at
flask/__init__.py
you will see thatabort
is actually imported fromwerkzeug.exceptions
. Looking at theAborter
class, we can see that when called with a numeric code, the particularHTTPException
subclass is looked up and called with all of the arguments provided to theAborter
instance. Looking atHTTPException
, paying particular attention to lines 85-89 we can see that the second argument passed toHTTPException.__init__
is stored in thedescription
property, as @dirn pointed out.You can either access the message from the
description
property:or just pass the description in by itself:
I simply do it like this: