Skip to content

Instantly share code, notes, and snippets.

@richpeck
Last active August 4, 2018 22:02
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save richpeck/8fcde2f91d10946528eb379c72cdec0e to your computer and use it in GitHub Desktop.
Save richpeck/8fcde2f91d10946528eb379c72cdec0e to your computer and use it in GitHub Desktop.
CONTROLLER Exception Handling In Rails
# config/application.rb
# This can be put in any of the "environment" files - config/application.rb is just the main
config.exceptions_app = ->(env) { ApplicationController.action(:exception).call(env) }
# If you want custom exceptions, you need to add new rescue_responses:
# http://guides.rubyonrails.org/configuring.html#configuring-action-dispatch
config.action_dispatch.rescue_response["Your::Exception"] = :bad_request
# app/controllers/exceptions_controller.rb
# This takes the exception request and returns the "show" view
class ApplicationController < ApplicationController
######################################
######################################
# => Exception
# => Set the @exception object
# => Since we've received the request, we can do what we want here
def exception
@exception = env['action_dispatch.exception']
@status = ActionDispatch::ExceptionWrapper.new(env, @exception).status_code
@message = ActionDispatch::ExceptionWrapper.rescue_responses[@exception.class.name]
render :exception, status: @status, layout: ("exception" if @status == 500)
end
######################################
######################################
end
# app/views/application/exception.html.erb
# Exception view
# This will remain constant for all erroneous responses, allowing us to change the layout only
<h1> Error <%= @status %></h1>
<p><%= @message %></p>
# app/views/layouts/exception.html.erb
# Exception layout designed to give you a 500 error page layout with no conflicts
<html>
<head>
<title><%= @status %> Error</title>
<%= stylesheet_include_tag :application # - you can include any CSS you want %>
</head>
<body>
<%= @message %>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment