python - Developing an error handler as a decorator in flask-restful -



python - Developing an error handler as a decorator in flask-restful -

i'm trying develop rest api flask-restful. next decorator implemented:

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

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

class docerror(exception): pass class docnotfound(docerror): pass

now problem implementation of these 2 classes in way homecoming optional error msg. don't know how that. please give me hint?

p.s. here way wanna utilize decorator in resources:

my_decorators = [ errorhandler, # other decorators ] class docs(resource): method_decorators = my_decorators def get(): .errors import docnotfound if (<something>): raise docnotfound('no access you!') homecoming marshal(......) def delete(): pass def put(): pass def post(): pass

thanks

you can raise custom exceptions argument:

raise docnotfound('the document "foo" on verboten list, no access you!')

then access message with:

except errors.docnotfound err: message = err.message or "wrong document requested" abort(404, description=message)

the abort(404) phone call maps werkzeug.exceptions.notfound exception; description argument lets override default description.

python flask flask-restful

Comments

Popular posts from this blog

Delphi change the assembly code of a running process -

json - Hibernate and Jackson (java.lang.IllegalStateException: Cannot call sendError() after the response has been committed) -

C++ 11 "class" keyword -