0

我有以下errors_controller.rb

class ErrorsController < ActionController::Base
layout 'bare'

def show
return render_error params[:id], :ok
end

def index
  request.format.to_s.downcase == 'application/json' ? json_error : html_error
  return
end

private

def exception
  env['action_dispatch.exception']
end

def html_error
  if exception.nil?
    render_error 404
  else
    render_error 500
  end
end

def json_error
  if exception.nil?
    render json: error_hash(:resource_not_found), status: 404
  else
    render json: error_hash(:internal_server_error), status: 500
  end
end

def error_hash(code)
  {
    errors: [
      {
        message: I18n.t("errors.api.#{code}"),
        code: code
      }
    ]
  }
end

def render_error(code, status_type = nil)
  @error = ErrorMessage.new(code, status_type)
  render @error.partial, status: @error.status
end
end

当向 /api/test.xml 发出请求时,它给了我

ActionView::MissingTemplate at /api/test.xml
Missing template messages/show with {:locale=>[:en], :formats=>[:xml],       :handlers=>[:erb, :builder, :raw, :ruby, :haml]}

我不想做

rescue_from(ActionController::MissingTemplate)

因为这将处理所有缺少模板的动作错误,即使 url 中有一些拼写错误。

我想要一种健康的方法来为任何请求(.xml,.jpeg,.....)抛出 404

尝试

我尝试添加before_filter仍然给我同样的错误。

config.action_dispatch.ignore_accept_header = true在application.rb中添加了,仍然没有运气。

谁能告诉我一些方向?先感谢您

4

1 回答 1

1

你可以做:

def render_error(code, status_type = nil)
  @error = ErrorMessage.new(code, status_type)
  respond_to do |format|
    format.any(:html, :json) { render @error.partial, status: @error.status }
    format.any { head 404, "content_type" => 'text/plain' }
  end
end
于 2015-03-13T16:04:28.720 回答