Custom error message json object with flask-restful


It is easy to propagate error messages with flask-restful to the client with the abort() method, such as

abort(500, message="Fatal error: Pizza the Hutt was found dead earlier today
in the back seat of his stretched limo. Evidently, the notorious gangster
became locked in his car and ate himself to death.")

This will generate the following json output

  "message": "Fatal error: Pizza the Hutt was found dead earlier today
       in the back seat of his stretched limo. Evidently, the notorious gangster
       became locked in his car and ate himself to death.", 
  "status": 500

Is there a way to customise the json output with additional members? For example:

  "sub_code": 42,
  "action": "redirect:#/Outer/Space"
  "message": "You idiots! These are not them! You've captured their stunt doubles!", 
  "status": 500

Answer 1:

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:

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

Answer 2:

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 HTTPException

class UserAlreadyExistsError(HTTPException):

custom_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.

Answer 3:

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, jsonify

response = make_response(jsonify(message="Message goes here"), 400)

Answer 4:

I disagree with @Miguel on the pertinence of abort(). Unless you're using Flask to build something other than an HTTP app (with the request/response paradigm), I believe that you should use as much of the HTTPExceptions as possible (see the werkzeug.exceptions module). It also means using the aborting mechanism (which is just a shortcut to these exceptions). If instead you opt to explicitly build and return your own errors in views, it leads you into a pattern where you need to check values with a series of if/else/return, which are often unnecessary. Remember, your functions are more than likely operating in the context of a request/response pipeline. Instead of having to travel all the way back to the view before making a decision, just abort the request at the failing point and be done with it. The framework perfectly understands and has contingencies for this pattern. And you can still catch the exception in case you need to (perhaps to supplement it with additional messages, or to salvage the request).

So, similar to @Miguel's but maintaining the intended aborting mechanism:

 def json_abort(status_code, data=None):
    response = jsonify(data or {'error': 'There was an error'})
    response.status_code = status_code

# then in app during a request

def check_unique_username(username):
    if UserModel.by__username(username):
        json_abort(409, {'error': 'The username is taken'})

def fetch_user(user_id): 
        return UserModel.get(user_id)
    except UserModel.NotFound:
        json_abort(404, {'error': 'User not found'})

Answer 5:

I had to define attribute code to my subclassed HttpException for this custom error handling to work properly:

from werkzeug.exceptions import HTTPException
from flask_restful import Api
from flask import Blueprint

api_bp = Blueprint('api',__name__)

class ResourceAlreadyExists(HTTPException):
    code = 400

errors = {
    'ResourceAlreadyExists': {
        'message': "This resource already exists.",
        'status': 409,

api = Api(api_bp, errors=errors)

and then later, raise the exception

raise ResourceAlreadyExists

Answer 6:

It's obviously late, but in the meanwhile Flask-RESTful managed to provide a cleaner way to handle errors, as pointed out by the docs.

Also the issue opened to suggest the improvement can help.

Answer 7:

Using Flask-RESTful (0.3.8 or higher)

from flask_restful import Api
customErrors = {
    'NotFound': {
        'message': "The resource that you are trying to access does not exist",
        'status': 404,
        'anotherMessage': 'Another message here'
    'BadRequest': {
        'message': "The server was not able to handle this request",
        'status': 400,
        'anotherMessage': 'Another message here'
app = Flask(__name__)
api = Api(app, catch_all_404s=True, errors=customErrors)

The trick is to use the exceptions from Werkzeug Docs

So for instance, if you want to handle a 400 request, you should add BadRequest to the customErrors json object.

Or if you want to handle 404 errors, then use NotFound in your json object and so on


码神部落- 版权声明 1、本主题所有言论和图片纯属会员个人意见,与码神部落立场无关。

最新回复 (0)
    • 码神部落
        立即登录 立即注册 GitHub登录