首页 > 解决方案 > 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

标签: ruby-on-railsexception

解决方案


正如@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

推荐阅读