Skip to content

Instantly share code, notes, and snippets.

@s-andringa
Created September 19, 2012 10:09
Show Gist options
  • Star 10 You must be signed in to star a gist
  • Fork 8 You must be signed in to fork a gist
  • Save s-andringa/3748828 to your computer and use it in GitHub Desktop.
Save s-andringa/3748828 to your computer and use it in GitHub Desktop.
Amsrb talk 18 sept - exceptions_app in Rails 3.2
# config/locales/en.yml
en:
exception:
show:
not_found:
title: "Not Found"
description: "The page you were looking for does not exists."
internal_server_error:
title: "Internal Server Error"
description: "Sorry, something went wrong while processing your request."
bad_request:
title: "Bad Request"
description: "The server did not understand your request. It may have been malformed."
bad_taste:
title: "Bad Taste"
description: "Sorry, the server thinks you've got a bad taste for food (%{exception_message})."
# config/environments/development.rb
config.consider_all_requests_local = false # true
# config/application.rb
config.exceptions_app = ->(env) { ExceptionController.action(:show).call(env) }
config.action_dispatch.rescue_responses["BadTaste"] = :bad_request
# app/controllers/exception_controller.rb
class ExceptionController < ActionController::Base
layout 'application'
def show
@exception = env['action_dispatch.exception']
@status_code = ActionDispatch::ExceptionWrapper.new(env, @exception).status_code
@rescue_response = ActionDispatch::ExceptionWrapper.rescue_responses[@exception.class.name]
respond_to do |format|
format.html { render :show, status: @status_code, layout: !request.xhr? }
format.xml { render xml: details, root: "error", status: @status_code }
format.json { render json: {error: details}, status: @status_code }
end
end
protected
def details
@details ||= {}.tap do |h|
I18n.with_options scope: [:exception, :show, @rescue_response], exception_name: @exception.class.name, exception_message: @exception.message do |i18n|
h[:name] = i18n.t "#{@exception.class.name.underscore}.title", default: i18n.t(:title, default: @exception.class.name)
h[:message] = i18n.t "#{@exception.class.name.underscore}.description", default: i18n.t(:description, default: @exception.message)
end
end
end
helper_method :details
end
# app/controllers/articles_controller.rb
class ArticlesController < ApplicationController
def show
# ...
raise BadTaste, "Clams are grose" if @article.title =~ /vongole/i
end
# ...
class ::BadTaste < ::StandardError; end
end
<!-- app/views/exception/show.htm.erb -->
<div class="box">
<h1><%= details[:name] %></h1>
<p><%= details[:message] %></p>
<%= link_to "Back to home", root_path %>
</div>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment