Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Raising A Custom Error with Flask-Restful

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.

like image 891
GG_Python Avatar asked Jan 12 '15 20:01

GG_Python


1 Answers

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.

like image 72
Alexandre Avatar answered Sep 18 '22 06:09

Alexandre