簡體   English   中英

在 Rails 4 中,來自 ActionController::RoutingError 的救援

[英]rescue_from ActionController::RoutingError in Rails 4

我有以下錯誤:

ActionController::RoutingError (No route matches [GET] "/images/favicon.ico")

我想為不存在的鏈接顯示 error404 頁面。

我怎樣才能做到這一點?

application_controller.rb添加以下內容:

  # You want to get exceptions in development, but not in production.
  unless Rails.application.config.consider_all_requests_local
    rescue_from ActionController::RoutingError, with: -> { render_404  }
  end

  def render_404
    respond_to do |format|
      format.html { render template: 'errors/not_found', status: 404 }
      format.all { render nothing: true, status: 404 }
    end
  end

我通常也會拯救以下異常,但這取決於你:

rescue_from ActionController::UnknownController, with: -> { render_404  }
rescue_from ActiveRecord::RecordNotFound,        with: -> { render_404  }

創建錯誤控制器:

class ErrorsController < ApplicationController
  def error_404
    render 'errors/not_found'
  end
end

然后在routes.rb

  unless Rails.application.config.consider_all_requests_local
    # having created corresponding controller and action
    get '*path', to: 'errors#error_404', via: :all
  end

最后一件事是在/views/errors/下創建not_found.html.haml (或您使用的任何模板引擎):

  %span 404
  %br
  Page Not Found

@Andrey Deineko,您的解決方案似乎僅適用於在RoutingError內手動引發的RoutingError s。 如果我使用 url my_app/not_existing_path嘗試它,我仍然收到標准錯誤消息。

我想這是因為應用程序甚至沒有到達控制器,因為 Rails 之前引發了錯誤。

為我解決問題的技巧是在路線的末尾添加以下行:

Rails.application.routes.draw do
  # existing paths
  match '*path' => 'errors#error_404', via: :all
end

捕獲所有未預定義的請求。

然后在 ErrorsController 中,您可以使用respond_to來處理 html、json... 請求:

class ErrorsController < ApplicationController
  def error_404
    @requested_path = request.path
    repond_to do |format|
      format.html
      format.json { render json: {routing_error: @requested_path} }
    end
  end
end

app/assets/images復制網站圖標圖像對我有用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM