如何从Ruby on Rails应用程序返回正确的HTTP错误代码

我有RoR 3.0 Web应用程序,它充当OAuth API提供程序。 现在,在API中我想向API使用者返回正确的HTTP错误代码。 我该怎么做呢?

这是一个例子:

def destroy_oauth @item = Item.find(params[:id]) if(!@item.nil? && @item.user_id == current_user.id) @item.destroy respond_to do |format| format.js format.xml end else raise ActionController::RoutingError.new('Forbidden') end end 

因此,如果出现错误,我正在尝试返回Forbidden 403代码。 仍然,当运行这个时,我总是得到404 Not Found返回。 如何返回正确的代码?

或者这是某种网络服务器可配置的东西?

您应该以正确的状态呈现页面。

 render(:file => File.join(Rails.root, 'public/403.html'), :status => 403, :layout => false) 

如果您只是提供状态代码并且没有正文,那么便捷的方式就是

 head 403 

此方法还接受状态代码的符号名称,例如

 head :forbidden 

根据ActionController :: Head文档,只需在动作中使用此模式

  return head([status]) if/unless [some condition here] 

例:

  return head(:gone) if @record.deleted? return head(:forbidden) unless @user.owns?(@record) 

return用于确保将不会运行操作中的剩余代码。

好吧,你可以使用

 :status =>500 

但是,在默认情况下,Rails会处理错误类型呈现本身。

错误默认页面位于公共目录中。 500.html,404.html等..

有关以下内容的更多信息:status ,如何使用它请单击此处

我认为你有两个问题:首先是你的@item = Item.find(params[:id])行正在提高404并且执行永远不会到达预期的位置( if语句)。 其次是你提出exception并且永远不会抓住它们。 尝试:

 def destroy_oauth begin @item = Item.find(params[:id]) if(!@item.nil? && @item.user_id == current_user.id) @item.destroy respond_to do |format| format.js format.xml end else raise ActionController::RoutingError.new('Forbidden') end rescue ActiveRecord::ResourceNotFound redirect_to :action => 'not_found', :status => 404 # do whatever you want here rescue ActionController::RoutingError redirect_to :action => 'forbidden', :status => 403 # do whatever you want here end end 

这些内容,但您还提到您正在构建API,因此当您挽救错误时,您可能希望呈现xml错误信息。 就像是:

 # in application_controller.rb rescue_from ActionController::RoutingError, :with => :render_forbidden_error private def render_forbidden_error(e) render :status => e.status, :xml => e end 

祝好运。 Udachi。