Last active
August 30, 2021 17:36
-
-
Save westonganger/0a711b834f41278f38023d25a15b0e0f to your computer and use it in GitHub Desktop.
How to successfully Throttle or use ignore_if option for exception_notification gem for Rails
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
### HOW TO IMPLEMENT EXCEPTION THROTTLING WITH EXCEPTION NOTIFIER FOR RAILS | |
### | |
### Documentation for Exception Notification: https://github.com/smartinez87/exception_notification | |
### SETUP VARIABLES | |
cache_key = "exception_times" | |
if ["development", "test"].include?(Rails.env.to_s) | |
throttle_interval = 0 ### no throttling for dev | |
else | |
throttle_interval = 5.minutes | |
end | |
### CALLBACK FOR ignore_if | |
throttle_error = ->(env, exception){ | |
exception_times = Rails.cache.read(cache_key) | |
if exception_times.nil? | |
Rails.cache.write({}) | |
end | |
### First Cleanup old exception times so hash doesnt get massive | |
exception_times.reject!{|k,v| v <= (Time.now - throttle_interval) } | |
### Define Identifier for grouping the exceptions (customize as needed) | |
identifier = [ | |
exception.name, | |
env.ip, | |
exception.backtrace.first, | |
].join("/") | |
### Throttle Logic | |
last_time = exception_times[identifier] | |
if last_time && Time.now <= (last_time + throttle_interval) | |
exception_times[identifier] = Time.now | |
throttle = false ### do not throttle the exception | |
else | |
throttle = true ### throttle the exception | |
end | |
### Save to Cache | |
Rails.cache.store("exception_times", exception_times) | |
next throttle | |
} | |
### Exception Notification Setup | |
Rails.application.config.middleware.use(ExceptionNotification::Rack, { | |
email: { | |
email_prefix: "[EXCEPTION] ", | |
sender_address: %{"Exception Notifier" <#{NOTIFICATIONS_EMAIL}>}, | |
exception_recipients: [DEV_EMAIL], | |
}, | |
ignore_if: throttle_error, | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment