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.

GG_Python
  • 3,436
  • 5
  • 34
  • 46
  • 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. – esdotzed Feb 15 '15 at 08:13

1 Answers1

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.

Arkady
  • 14,305
  • 8
  • 42
  • 46
Alexandre
  • 1,635
  • 14
  • 21
  • 1
    I'm having a lot of trouble with the above: *** TypeError: abort() takes exactly 1 argument (2 given) – Kelvin Jun 02 '16 at 14:58
  • 1
    @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. – herrherr Jan 03 '18 at 10:36
  • @Kelvin try abort(409, message="A user with that username already exists.") – Handsome Greg Oct 19 '20 at 04:00