rails自定义出错页面

一、出错类型

Exception

ActionController::UnknownController,

ActiveRecord::RecordNotFound

ActionController::RoutingError

AbstractController::ActionNotFound

二、解决方案

1、在你的app/controllers/application_controller.rbApplicationController里面用rescue_from捕捉他们,并且只在生产环境这样做

class ApplicationController < ActionController::Base
  unless Rails.application.config.consider_all_requests_local
    rescue_from Exception, with: lambda { |exception|
      render_error 500, exception
    }
    rescue_from ActionController::UnknownController, ActiveRecord::RecordNotFound, with: lambda { |exception|
      render_error 404, exception
    }
  end

2、然后加上render_error方法,用来渲染报错页面,你可以在这里做定制渲染

def render_error(status, exception)
  respond_to do |format|
    format.html { render template: "errors/error_#{status}", layout: 'layouts/application', status: status }
    format.all { render nothing: true, status: status }
  end
end

3、还是有一个问题,无法捕捉ActionController::RoutingErrorAbstractController::ActionNotFound,需要在config/route.rb里面最后捕捉

unless Rails.application.config.consider_all_requests_local
  match '*not_found', to: 'errors#error_404'
end

4、加上errors_controller.rb,代码如下

class ErrorsController < ApplicationController
  def error_404
    @not_found_path = params[:not_found]
    render_error 404, nil
  end

三、开发环境下测试错误信息页面

因为开发环境下出现错误,都会呈现对应的错误信息,包括代码位置等。而不会弹出404或500页面,其实要在开发环境下,检测这些页面也是很方便的

# config/environments/development.rb
config.consider_all_requests_local = false

只需要把上面的设置从true改为false就可以了。

四、参考

http://blog.linjunhalida.com/blog/rails-customize-error-page/?utm_source=tuicool&utm_medium=referral

https://ruby-china.org/topics/21413

原文地址:https://www.cnblogs.com/zs-note/p/7000966.html