Search code examples
flaskflask-restful

Custom error handler in flask_restful throws NameError


I am trying to add a custom error code to a flask_restful API, following the directions given in the docs however I do not receive the correct response and I am getting a NameError: global name 'UnsupportedMediaType' is not defined message. What am I doing wrong here?

# -*- coding: utf-8 -*-

from flask import Flask, request
from flask_restful import Resource, Api

import service

errors = {
    'UnsupportedMediaType': {
        'message': 'Unsupported Media Type',
        'status': 415
    }
}

app = Flask(__name__)
api = Api(app, errors=errors)

class Service(Resource):
    def post(self):
        if request.is_json:
            data = request.get_json()
            return service.handler(args['data'])
        else:
            raise UnsupportedMediaType

api.add_resource(Service, '/')

if __name__ == '__main__':
    app.run(host='0.0.0.0', debug=True)

Solution

  • You must store the error handler to a function. Like this:

    def error(exception): return {some json error data with the message 'exception'}

    now you can call the error handler as you want.

    OR

    You can use Flask error handler decorator for that. Heres the link