V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
keysona
V2EX  ›  Python

tornado 使用抛异常来返回 json 错误响应

  •  
  •   keysona · 2017-06-13 12:23:10 +08:00 · 1473 次点击
    这是一个创建于 2516 天前的主题,其中的信息可能已经有所发展或是发生改变。
    最近在写 api 时,对错误响应的感觉处理很别扭。

    是 True / False

    还是封装一个 result 类。

    纠结了会,发现,异常好像很好用。
    5 条回复    2017-06-14 18:42:02 +08:00
    wentian
        1
    wentian  
       2017-06-13 12:33:49 +08:00
    封装 Result 是最好的

    {
    "err_code":
    "err_msg":
    "detail"
    }
    LeeSeoung
        2
    LeeSeoung  
       2017-06-13 15:08:15 +08:00
    {
    "success":true
    "data":
    "message":error_msg
    }
    swulling
        3
    swulling  
       2017-06-13 15:12:31 +08:00
    我推荐是两者组合。

    如果正常返回的结果直接就是 data 本身
    如果是 4XX 或者 5XX,除了错误码之外,定义一个异常的 json 即可,一般是"success": true/fasle,"message" : "xxxx"

    tornado 可以自定义 errorhandler 来做到这个
    honmaple
        4
    honmaple  
       2017-06-13 16:12:27 +08:00
    {
    "status":"",
    "message":"",
    "description":"",
    "data":{}
    }
    我比较喜欢这样的,status 自定义状态码,200 为 success,message 返回相关信息
    TimePPT
        5
    TimePPT  
       2017-06-14 18:42:02 +08:00
    status code + message
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2236 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 06:49 · PVG 14:49 · LAX 23:49 · JFK 02:49
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.