我试图测试通过请求 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 经验出现
使用ActionController::MimeResponds
而不是糟糕地重新发明轮子:
# or whatever your base controller class is
class ApplicationController < ActionController::API
# MimeResponds is not included in ActionController::API
include ActionController::MimeResponds
# Defining this in your parent class avoids repeating the same error handling code
rescue_from ActionController::UnknownFormat do
raise DRI::Exceptions::NotImplemented # do you really need to add another layer of complexity?
end
end
module Api
class OembedController < ApplicationController
def oembed
respond_to :json
end
end
end
如果不使用respond_to
则 Rails 将隐式假定控制器响应所有响应格式。但是,如果您使用符号列表(或更常见的块语法)明确列出您响应的格式,则如果未列出请求格式,Rails 将引发ActionController::UnknownFormat
。您可以使用rescue_from
来拯救异常,这允许您使用继承,而不是使用相同的错误处理重复自己。
正如@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