← 返回题库
初级

API错误码体系设计

未完成
初级参考 完整示例代码供参考,建议自己理解后重新输入
def solve():
    from pyodide.http import open_url
    from io import StringIO
    users_csv = open_url("https://data.zuihe.com/dbd/ms-shop/state_00/users.csv").read()
    ERROR_CODES = {
        100101: ('用户不存在', 404),
        100102: ('用户已被封禁', 403),
        100103: ('用户名已存在', 409),
        100201: ('商品不存在', 404),
        100202: ('库存不足', 400),
        100301: ('订单不存在', 404),
        100302: ('订单状态不允许此操作', 400),
        500001: ('数据库连接失败', 500),
        500002: ('内部服务错误', 500),
    }
    def make_error(code, detail=None):
        msg, http_code = ERROR_CODES.get(code, ('未知错误', 500))
        r = {'code': code, 'msg': msg, 'http_status': http_code}
        if detail: r['detail'] = detail
        return r
    for code in [100101, 100202, 100302, 500001]:
        e = make_error(code)
        print(f"code={code}: msg={e['msg']}, http={e['http_status']}")

示例

输入
solve()
期望输出
code=100101: msg=用户不存在, http=404
code=100202: msg=库存不足, http=400
code=100302: msg=订单状态不允许此操作, http=400
code=500001: msg=数据库连接失败, http=500
Python 代码 🔒 登录后使用
🔒

登录后即可练习

注册免费账号,在浏览器中直接运行 Python 代码