REST API中的普通(非HTML)错误页面 [英] Plain (non-HTML) error pages in REST api

查看:57
本文介绍了REST API中的普通(非HTML)错误页面的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用Flask编写一个简单的REST服务.当我的代码中发生异常时,我会在浏览器中收到一条不错的错误消息和一个交互式调试器.但是,如果我从命令行(例如使用curl)或在单元测试中调用该服务,但出现故障,我仍然会收到格式化的(HTML)错误消息.我记得有时我会收到一条纯文本消息(基本上只是Python错误+追溯),而且我不知道Flask如何决定提供纯文本或HTML.

I'm writing a simple REST service with Flask. When an exception occurs in my code, I get a nice error message and an interactive debugger in my browser. However, if I call the service from the command line (e.g. with curl), or in my unit tests, and something fails, I still get the formatted (HTML) error message. I remember that I sometimes got a plain text message instead (basically just the Python error + traceback), and I don't know how Flask decides to serve plain text or HTML.

如何使Flask在不使用浏览器进行访问时返回普通(非交互式,非HTML)错误消息?

How do I make it so that Flask returns plain (non-interactive, non-HTML) error messages when accessed without a browser?

推荐答案

要在生产模式下处理异常,请为500个状态码注册错误处理程序.从中您可以返回任何想要的东西.这是一个将异常本身作为纯文本返回的示例:

To handle exceptions in production mode, register error handler for 500 status code. From it you can return anything you want. Here's an example that returns exception itself as plain text:

@app.errorhandler(500)
def error_500(exception):
    return str(exception), 500, {'Content-Type': 'text/plain'}

如果您正在编写的是API,则将JSON编码的数据作为 application/json 返回可能更合适.

If it's API you're writing, returning JSON encoded data as application/json may be more appropriate.

这篇关于REST API中的普通(非HTML)错误页面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆