Custom error message json object with flask-restful Custom error message json object with flask-restful flask flask

Custom error message json object with flask-restful


People tend to overuse abort(), while in fact it is very simple to generate your own errors. You can write a function that generates custom errors easily, here is one that matches your JSON:

def make_error(status_code, sub_code, message, action):    response = jsonify({        'status': status_code,        'sub_code': sub_code,        'message': message,        'action': action    })    response.status_code = status_code    return response

Then instead of calling abort() do this:

@route('/')def my_view_function():    # ...    if need_to_return_error:        return make_error(500, 42, 'You idiots!...', 'redirect...')    # ...


I don't have 50 reputation to comment on @dappiu, so I just have to write a new answer, but it is really related to "Flask-RESTful managed to provide a cleaner way to handle errors" as very poorly documented here

It is such a bad document that took me a while to figure out how to use it. The key is your custom exception must inherit from flask_restful import HTTPException. Please note that you cannot use Python Exception.

from flask_restful import HTTPExceptionclass UserAlreadyExistsError(HTTPException):    passcustom_errors = {    'UserAlreadyExistsError': {        'message': "A user with that username already exists.",        'status': 409,    }}api = Api(app, errors=custom_errors)

Flask-RESTful team has done a good job to make custom exception handling easy but documentation ruined the effort.


As @Miguel shows, normally you shouldn't use exceptions, just return some error response. However, sometimes you really need an abort mechanism that raises an exception. This may be useful in filter methods, for example. Note that flask.abort accepts a Response object (check this gist):

from flask import abort, make_response, jsonifyresponse = make_response(jsonify(message="Message goes here"), 400)abort(response)