【问题标题】:Error handler is not invoked in production生产中未调用错误处理程序
【发布时间】:2014-07-23 12:07:16
【问题描述】:

当我使用 Flask 开发服务器并引发异常时,我会得到正确的错误代码和我的自定义错误消息。但这在生产环境中不起作用(我将 lighttpd 与 fcgi 一起使用),我只是在那里得到 500 错误。

我的异常如下所示:

class InvalidSettings(Exception):
    status_code = 400

    def __init__(self, message, status_code=None, payload=None):
        super(InvalidSettings, self).__init__()
        self.message = message
        if status_code is not None:
            self.status_code = status_code
        self.payload = payload

    def to_dict(self):
        rv = dict(self.payload or ())
        rv['message'] = self.message
        return rv

这是错误处理程序代码:

@app.errorhandler(InvalidSettings)
def handle_invalid_settings(error):
    response = json.dumps(error.to_dict())
    response.status_code = error.status_code
    return response

更新

我尝试使用custom error messages,但出现异常:

TypeError: __init__() got an unexpected keyword argument 'errors'

的确如此,Flask-RESTful 中的 Api 构造函数中没有这样的东西。这很奇怪,因为它是 0.2.1 版本的文档,正如我在 pip 中看到的那样,我的版本是 0.2.12。但是,我不知道它是否是我真正需要的。

【问题讨论】:

  • 服务器日志中是否有任何堆栈跟踪?

标签: python flask flask-restful


【解决方案1】:

我从 master 分支安装了最新版本,errors 构造函数有 errors 参数。

现在它在我稍微更改代码后返回正确的异常,正如documentation 建议的那样:

errors = {
    'InvalidSettings': {
        'message': "Something is wrong with your settings",
        'status': 400,
    }
}
api = restful.Api(app, errors=errors)

但是还有一个问题,也许我在文档中遗漏了一些东西。如何从我提出的地方传递消息?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-02
    相关资源
    最近更新 更多