Rails dynamic error pages (404, 422, 500) showing as blank

元气小坏坏 提交于 2019-12-08 03:51:14

问题


I'm implementing dynamic error pages into an app, and have a feeling it's looking in the public folder for (now non-existent) templates, rather than following the routes I've set up.

In config/application.rb I've added the line config.exceptions_app = self.routes to account for this.

I've then added the following to my routes:

get "/not-found", :to => "errors#not_found"
get "/unacceptable", :to => "errors#unacceptable"
get "/internal-error", :to => "errors#internal_error"

And the errors controller looks like so:

class ErrorsController < ApplicationController
  layout 'errors'
  def not_found
    render :status => 404
  end

  def unacceptable
    render :status => 422
  end

  def internal_error
    render :status => 500
  end
end

Going to /not-found shows the template as it should be, though visiting any non-existing URL (i.e. /i-dont-exist) renders an empty page.

The only reason I could see for this would be that the exception handling needs the routes to be, for example, get "/404", :to => "errors#not_found", though, ironically, it's not finding the route for /404 (and no, that's not just it working :) ).

Any advice, greatly appreciated. Thanks, Steve.


回答1:


It seems some setting is wrong. Try this in your routes:

match '/404', to: 'errors#not_found', via: :all (match instead of get)

You mention that in application.rb you have config.exceptions_app = self.routes, that is good. But make sure you are restarting the server before testing your changes.

And make sure your error views files have the same name than the actions in your ErrorsController.

If you are getting any kind of (haha) error in the console, could you post it?




回答2:


Do this instead:

routes.rb

%w(404 422 500).each do |code|
  get code, :to => "errors#show", :code => code
end

errors_controller.rb

class ErrorsController < ApplicationController
  def show
    render status_code.to_s, :status => status_code
  end

  protected
  def status_code
    params[:code] || 500
  end
end

inside your config/application.rb ensure you have:

module YourWebsite
  class Application < Rails::Application

    config.exceptions_app = self.routes
    # .. more code ..
  end
end

Then you will need the views, obviously ;) don't forget to remove the error pages in your public directory as well.



来源:https://stackoverflow.com/questions/33149971/rails-dynamic-error-pages-404-422-500-showing-as-blank

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