Search code examples
pythonflaskflask-restful

Developing an error handler as a decorator in flask-restful


I'm trying to develop a rest api by flask-restful. The following decorator is implemented:

def errorhandler(f):
    @wraps(f)
    def wrapper(*args, **kwargs):
        try:
            return f(*args, **kwargs)
        except errors.DocNotFound:
            abort(404, message="Wrong document requested", status=404)
    return wrapper

And, Following https://docs.python.org/2/tutorial/errors.html#user-defined-exceptions , in another file named error.py (which is imported here), I have these classes:

class DocError(Exception):
       pass

class DocNotFound(DocError):
       pass

Now my problem is the implementation of these 2 classes in a way that return my optional error msg. But I don't know how to do that. Would you please give me a hint?

P.S. Here is the way I wanna use the decorator in my Resources:

my_decorators = [
    errorhandler,
    # Other decorators
]
class Docs(Resource):
    method_decorators = my_decorators

    def get():
       from .errors import DocNotFound
       if (<something>):
             raise DocNotFound('No access for you!')
       return marshal(......)

    def delete():
        pass

    def put():
        pass

    def post():
        pass

Thanks


Solution

  • You can raise your custom exceptions with an argument:

    raise DocNotFound('The document "foo" is on the verboten list, no access for you!')
    

    then access that message with:

    except errors.DocNotFound as err:
        message = err.message or "Wrong document requested"
        abort(404, description=message)
    

    The abort(404) call maps to a werkzeug.exceptions.NotFound exception; the description argument lets you override the default description.