ruby-on-rails - Rails 中格式不正确的异常
问题描述
我试图测试通过请求 url 发送的格式是否是 json?
所以在link_to中我发送了这样的格式
<%= link_to "Embed", {:controller=>'api/oembed' ,:action => 'show',:url => catalog_url, format: 'xml'} %>
在相关控制器中,我捕获参数并引发这样的异常
format_request = params[:format]
if format_request != "json"
raise DRI::Exceptions::NotImplemented
end
但是不会显示异常,而是服务器只是遇到了内部错误,但是如果我更改了控制器内部的参数,则会显示异常,所以如果 url 是这样的
<%= link_to "Embed", {:controller=>'api/oembed' ,:action => 'show',:url => catalog_url, format: 'json'} %>
format_request = "xml"
if format_request != "json"
raise DRI::Exceptions::NotImplemented
end
如果我在 url 中以 xml 格式发送格式,为什么不会触发 501 异常?我这样做是为了测试目的,以防有人发送格式错误的请求 501 expetion
解决方案
正如@max 提到的,发送format: 'xml'
是不必要的,因为 Rails 已经知道请求的格式。
<%= link_to "Embed", {:controller=>'api/oembed' ,:action => 'show',:url => catalog_url } %>
在控制器中:
def oembed
respond_to do |format|
format.json { # do the thing you want }
format.any(:xml, :html) { # render your DRI::Exceptions::NotImplemented }
end
end
或者,如果您想要更多控制权,您可以使用自定义操作:
def oembed
respond_to do |format|
format.json { # do the thing you want }
format.any(:xml, :html) { render not_implemented }
end
end
def not_implemented
# just suggestions here
flash[:notice] = 'No support for non-JSON requests at this time'
redirect_to return_path
# or if you really want to throw an error
raise DRI::Exceptions::NotImplemented
end
如果你真的想重新发明轮子(这是你的轮子,如果你想重新发明):
我会重命名format
为其他名称,它可能已保留,可能会给您带来问题
<%= link_to "Embed", {:controller=>'api/oembed' ,:action => 'show',:url => catalog_url, custom_format: 'xml'} %>
然后,在您的控制器中,您需要明确允许此参数:
def oembed
raise DRI::Exceptions::NotImplemented unless format_params[:custom_format] == 'json'
end
private
def format_params
params.permit(:custom_format)
end
推荐阅读
- javascript - 递归展平数组(为什么我的函数不起作用?)
- openssl - google-cloud-kms PKCS7 加密消息语法
- python - 熊猫数据透视表并按多个值排序
- r - 更改传单中的图例箱大小
- python - 绘图后使用 glOrtho 函数而不重绘整个屏幕
- python - typeerror 不支持 ^ 的操作数类型:python 和 fusion360 中的“float”和“float”
- delphi - 将 TDirect2DCanvas 与 Font Awesome 图标一起使用
- python - 如何使用 Python 替换文本文件的多行中的某些字符?
- cassandra - 如何按 Cassandra 中的二级索引或列对结果进行排序?
- python - 带有可选文本的电话号码正则表达式,在在线工具上运行良好,但在我的代码中却不行