Add notifications to ActionDispatch::ShowExceptions, this can be used as hooks for plugins like ExceptionNotifier.

This commit is contained in:
José Valim 2010-01-03 23:33:34 +01:00
parent 6fbe9ef2ff
commit 53c6984944
2 changed files with 42 additions and 2 deletions

@ -1,7 +1,24 @@
require 'active_support/core_ext/exception'
require 'active_support/notifications'
require 'action_dispatch/http/request'
module ActionDispatch
# This middleware rescues any exception returned by the application and renders
# nice exception pages if it's being rescued locally.
#
# Every time an exception is caught, a notification is published, becoming a good API
# to deal with exceptions. So, if you want send an e-mail through ActionMailer
# everytime this notification is published, you just need to do the following:
#
# ActiveSupport::Notifications.subscribe "action_dispatch.show_exception" do |name, start, end, instrumentation_id, payload|
# ExceptionNotifier.deliver_exception(start, payload)
# end
#
# The payload is a hash which has to pairs:
#
# * :env - Contains the rack env for the given request;
# * :exception - The exception raised;
#
class ShowExceptions
LOCALHOST = '127.0.0.1'.freeze
@ -44,8 +61,11 @@ def initialize(app, consider_all_requests_local = false)
def call(env)
@app.call(env)
rescue Exception => exception
raise exception if env['action_dispatch.show_exceptions'] == false
render_exception(env, exception)
ActiveSupport::Notifications.instrument 'action_dispatch.show_exception',
:env => env, :exception => exception do
raise exception if env['action_dispatch.show_exceptions'] == false
render_exception(env, exception)
end
end
private

@ -104,4 +104,24 @@ class ShowExceptionsTest < ActionController::IntegrationTest
assert_response 405
assert_match /ActionController::MethodNotAllowed/, body
end
test "publishes notifications" do
@app, event = ProductionApp, nil
self.remote_addr = '127.0.0.1'
ActiveSupport::Notifications.subscribe('action_dispatch.show_exception') do |*args|
event = args
end
get "/"
assert_response 500
assert_match /puke/, body
ActiveSupport::Notifications.notifier.wait
assert_equal 'action_dispatch.show_exception', event.first
assert_kind_of Hash, event.last[:env]
assert_equal 'GET', event.last[:env]["REQUEST_METHOD"]
assert_kind_of RuntimeError, event.last[:exception]
end
end