gem 'gaffe' 异常页面美化

参考链接:https://github.com/mirego/gaffe

step1. gem ‘gaffe’

step2. bundle install

step3. 在 config/initializers/gaffe.rb 中写入

1
2
3
4
5
6
# config/initializers/gaffe.rb
Gaffe.configure do |config|
config.errors_controller = 'ErrorsController'
end
Gaffe.enable!

step4. 创建ErrorsController

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class ErrorsController < ApplicationController
include Gaffe::Errors
# Make sure anonymous users can see the page
skip_before_action :authenticate_user!
# Override 'error' layout
layout 'application'
# Render the correct template based on the exception “standard” code.
# Eg. For a 404 error, the `errors/not_found` template will be rendered.
def show
# Here, the `@exception` variable contains the original raised error
render "errors/#{@rescue_response}", status: @status_code
end
end

step5. 创建自己的(也可以用它默认的),目录为views/errors/not_found.erb 这种。如下图是这个gem的文件,我们可以覆盖:

step6. 修改config/environments/development.rb,可以看到报错的页面都会给特定的页面,比如404.erb等,但是在开发或者测试环境还是不要设置,因为错误信息看不到,我们自己不好看错误。(Rails prefers to render its own debug-friendly errors in the development environment, which is totally understandable. However, if you want to test Gaffe’s behavior in development you’ll have to edit the config/environments/development.rb file.)

1
2
# Make Rails use `exceptions_app` in development
config.consider_all_requests_local = false

测试环境可以这样干:
config/environments/test.rb

1
2
3
4
5
# Make Rails use `exceptions_app` in tests
config.consider_all_requests_local = false
# Render exceptions instead of raising them
config.action_dispatch.show_exceptions = true