【问题标题】:Rails handling 404's differently for different request typesRails 针对不同的请求类型以不同的方式处理 404
【发布时间】:2014-10-23 09:11:22
【问题描述】:

我在同一个应用程序(但不同的控制器和命名空间)中有一个 API 作为标准视图和控制器来处理相同的资源。

目前,当我收到 404 时,无论请求是以 HTML 还是 json 格式发出的,我都会收到 HTML 404 响应。

应用程序控制器部分处理 404 如下:

unless Rails.application.config.consider_all_requests_local
      rescue_from ActiveRecord::RecordNotFound, with: :render_denied_404
      rescue_from ActionController::RoutingError, with: :render_404
      rescue_from ::AbstractController::ActionNotFound, with: :render_404
      rescue_from ActionController::UnknownController, with: :render_404
      rescue_from ActionView::MissingTemplate, with: :render_404
end

def render_404(e = Exception.new)
      Rails.logger.info "Rendering 404: #{e.to_s}"
      flash[:error] = "Error 404 " + e.to_s
      redirect_to "/404"
end

如何更改此设置以根据请求格式类型以不同方式处理 404 错误?

【问题讨论】:

    标签: ruby-on-rails-3 routing


    【解决方案1】:

    您需要使用 respond_torespond_with 块根据您想要的响应方式做出不同的响应。

    API documentation

    Blog Article

    Rails Cast

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-05-07
      • 2020-03-02
      • 2014-06-28
      • 2011-12-14
      • 2015-10-18
      • 2013-03-30
      • 2020-08-26
      相关资源
      最近更新 更多