Raising A Custom Error with Flask-Restful

后端 未结 1 436
遥遥无期
遥遥无期 2021-02-07 21:32

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 do

相关标签:
1条回答
  • 2021-02-07 22:11

    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.

    0 讨论(0)
提交回复
热议问题