Custom error enhancement with Flask-Restful

That's it, I'm trying to raise a custom error using Flask-Restful, after. For testing purposes, I defined and registered an error dictionary that is precisely related in the documents: api = flask_restful.Api(app, errors=errors) .

However, when I want to raise a user error using (for example) abort(409) within the resource module, firebug reports:

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

This is similar to standard 409 error, nothing common; from the documents, I would expect a user error message: "A user with this username already exists."

I think that I am missing something related to raising the error itself. Should I use the dictionary key in any way? The Flask-Restful source code review did not help, although I tried.

+8
flask flask-restful
source share
1 answer

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

Following your question, consider an example of overriding Conflict exception :

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

Therefore, every time you call abort(409) , it returns a view in the right media type and with a specific message.

However, using this method, anywhere you break the 409 status code, this will return a user message with an existing username. It is unlikely that you want it when you call abort(409) in a view that deals with resources other than users.

So, I advise you to simply use the abort Flask-RESTful method 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, the Flask-RESTful extension by defining custom error messages is useful when you raise custom exceptions (with raise() rather than abort() ) that are not in the HTTP exceptions provided by Werkzeug.

+13
source share

All Articles