rescue_from ActionController::RoutingError in Rails 4

≡放荡痞女 提交于 2019-11-26 09:45:18

问题


I\'ve got the following error:

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

I want to show error404 page for links that are not existing.

How can I achieve that?


回答1:


In application_controller.rb add the following:

  # 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

I usually also rescue following exceptions, but that's up to you:

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

Create the errors controller:

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

Then in 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

And the last thing is to create not_found.html.haml (or whatever template engine you use) under /views/errors/:

  %span 404
  %br
  Page Not Found



回答2:


@Andrey Deineko, your solution seems to work only for the RoutingErrors raised manually inside a conrtoller. If I try it with the url my_app/not_existing_path, I still get the standard error message.

I guess this is because the application doesn't even reach the controllers, since Rails raises the error before.

The trick that solved the problem for me was to add the following line at the end of the routes:

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

to catch all not predefined requests.

Then in the ErrorsController you can use respond_to to serve html, json... requests:

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



回答3:


Copying favicon image in app/assets/images worked for me.



来源:https://stackoverflow.com/questions/25841377/rescue-from-actioncontrollerroutingerror-in-rails-4

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!