Custom 404 and 500 Error Pages in Rails

When an exception occurs, the goal is always to handle it gracefully. A red page full of errors appears extremely unprofessional.

Screen Shot 2020-09-27 at 11.16.14 PM.png

Here are some tips on handling errors more elegantly. First, add the following line in config/application.rb:

1
2
3
# config/application.rb

config.exceptions_app = self.routes

Next, create a controller - ErrorsController - and put the following code in it:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# app/controllers/errors_controller.rb

class ErrorsController < ApplicationController
 def not_found
   render status: 404
 end

 def internal_server
   render status: 500
 end

 def unprocessable
   render status: 422
 end

 def unacceptable
   render status: 406
 end
end

In config/routes.rb, define these routes:

1
2
3
4
5
# config/routes.rb

get '/404', to: 'errors#not_found'
get '/500', to: 'errors#internal_server'
get '/422', to: 'errors#unprocessable'

Now, delete these pages from the public folder:

public/404.html public/422.html public/500.html

Then create the following views in the app/views/errors directory:

1
2
3
touch app/views/errors/not_found.html.erb
touch app/views/errors/unprocessable.html.erb
touch app/views/errors/internal_server.html.erb

Finally, put the following lines in touch app/views/errors/not_found.html.erb:

1
2
3
<%# app/views/errors/not_found.html.erb %>

This page does not exist. Please go back.

Now if any record or page doesn’t exist, the new page will handle it gracefully. Happy handling!