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
谢谢
1 个解决方案
#1
66
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
你可以从架子上得到所有的状态码。Rails将象征的状态传递给机架
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_code
method. It's fun to read the source code!
向下滚动一点,您将看到status_code方法。阅读源代码很有趣!
#1
66
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
你可以从架子上得到所有的状态码。Rails将象征的状态传递给机架
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_code
method. It's fun to read the source code!
向下滚动一点,您将看到status_code方法。阅读源代码很有趣!