在flask-restful中开发装饰器形式的错误处理器

0 投票
1 回答
2371 浏览
提问于 2025-04-29 12:09

我正在尝试用flask-restful开发一个REST API。下面是我实现的一个装饰器:

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

接下来,按照这个链接的说明,在另一个名为error.py的文件中(这里已经导入了),我有这些类:

class DocError(Exception):
       pass

class DocNotFound(DocError):
       pass

现在我遇到的问题是,如何实现这两个类,以便返回我想要的可选错误信息。但我不知道该怎么做。你能给我一点提示吗?

附注:这是我想在我的资源中使用装饰器的方式:

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

谢谢

暂无标签

1 个回答

1

你可以通过传递一个参数来抛出你自定义的异常:

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

然后可以用以下方式访问这个消息:

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

abort(404) 这个调用对应的是一个 werkzeug.exceptions.NotFound 异常;而 description 参数可以让你自定义默认的描述信息。

撰写回答