bibi45

2020-05-05 | Backend 中文

Flask JSON 响应与错误处理

bibi45

为成功和失败响应建立稳定结构,同时避免泄露内部异常。

This article is currently available in Chinese. The language switch changes the site interface; the original text is shown below.

API 应返回 JSON 和正确 HTTP 状态码,而不是把错误堆栈或数据库信息暴露给客户端。

@app.errorhandler(NotFoundError)
def handle_not_found(error):
    return {"error": "not_found", "message": "Resource not found"}, 404

400 表示输入无效,401 表示未认证,403 表示已认证但无权限,404 不应帮助攻击者枚举敏感资源。未处理异常记录到受控日志,客户端只得到通用 500 响应。

© 2026 bibi45. All rights reserved.

Built as a static, Git-owned site.