Rails 3:如何在 JSON 请求中返回错误?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6004536/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 17:50:54  来源:igfitidea点击:

Rails 3: How to return errors in a JSON request?

jsonruby-on-rails-3api

提问by donald

How can I return a 800, 404, etc error when a user makes a JSON/XML request to my API?

当用户向我的 API 发出 JSON/XML 请求时,如何返回 800、404 等错误?

I've tried

我试过了

error 404, {:error => "ERror".to_json }

with no success.

没有成功。

Also, I've tried to put a "respond_to" but it doesn't work as well (it duplicates the respond_to and gives error).

另外,我尝试放置一个“respond_to”,但效果不佳(它复制了respond_to并给出了错误)。

Thanks

谢谢

回答by oma

The same way you return such errors with html, it's part of the HTTP Header.

与使用 html 返回此类错误的方式相同,它是 HTTP 标头的一部分。

render json: @myobject, status: :unprocessable_entity


Update, response to comment:

更新,回复评论:

You can get all the status codes from Rack. Rails passes the symbolized status to Rack

您可以从 Rack 获取所有状态代码。Rails 将符号状态传递给 Rack

Rack::Utils.status_code(options[:status])

which simply matches the symbol to the list of status (the strings are converted to symbols) Here is the smoking fresh list: https://github.com/rack/rack/blob/master/lib/rack/utils.rb#L575-L638

它只是将符号与状态列表匹配(字符串被转换为符号)这是吸烟新鲜列表:https: //github.com/rack/rack/blob/master/lib/rack/utils.rb#L575 -L638

Scroll a bit lower and you'll see the status_codemethod. It's fun to read the source code!

向下滚动一点,您将看到该status_code方法。阅读源代码很有趣!