Raising A Custom Error with Flask-Restful

GG_Python picture GG_Python · Jan 12, 2015 · Viewed 8.6k times · Source

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.

Answer

Alexandre picture Alexandre · Mar 24, 2015

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.