Skip to content

Instantly share code, notes, and snippets.

@chunlea
Forked from wojtha/Locales.yaml
Last active August 29, 2015 14:10
Show Gist options
  • Save chunlea/6f6381442be0c832e2d7 to your computer and use it in GitHub Desktop.
Save chunlea/6f6381442be0c832e2d7 to your computer and use it in GitHub Desktop.
# 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