13

All, I'm trying to raise a custom error using Flask-Restful, following the docs. For testing purposes, I've defined and registered the errors dictionary exactly link in the docs: api = flask_restful.Api(app, errors=errors).

However, when I want to raise the custom error using (e.g.) abort(409) within the resource module, firebug reports:

{ "message": "Conflict", "status": 409 }

This seems like the standard 409 error, nothing custom; from the docs, I would expect the custom error message- "A user with that username already exists."

I think I'm missing something regarding the raising of the error itself. Should I use the dictionary key in any way? Reviewing the Flask-Restful source code didn't help, though I tried.

1
  • 2
    Same here. If I defined 3 different errors for 400, how can I raise those errors? In the doc it says it saves try and catch in api function, but I don't see a clear way how that can be done. Commented Feb 15, 2015 at 8:13

1 Answer 1

20

To define a message for a standard HTTP status code with Flask-RESTful, you must redefine one of the HTTP exceptions provided by Werkzeug, on which Flask is based.

Following your question, here is an example to override the Conflict exception:

errors = { 'Conflict': { 'message': "A user with that username already exists.", 'status': 409, }, } app = Flask(__name__) api = flask_restful.Api(app, errors=errors) 

Hence, every time you will call abort(409), this will return a representation in the right mediatype, and with the defined message.

However, by using this method, in any place you will abort with a 409 status code, this will return a message about a user with a username that already exists. This is unlikely what you want when you call abort(409) in a view that deals with other resources than users.

So, I advise you to simply use the abort method of Flask-RESTful as follows, every time you want to provide a custom message:

from flask.ext.restful import abort abort(409, description="A user with that username already exists.") 

Generally speaking, extending Flask-RESTful by defining custom error messages is useful when you raise custom exceptions (with raise(), not abort()) which are not in the HTTP exceptions provided by Werkzeug.

Sign up to request clarification or add additional context in comments.

3 Comments

I'm having a lot of trouble with the above: *** TypeError: abort() takes exactly 1 argument (2 given)
@Kelvin make sure that you import the abort from flask and not from flask_restful. That was the reason for me that I received this error.
@Kelvin try abort(409, message="A user with that username already exists.")

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.