Last active
March 29, 2017 13:12
-
-
Save scan/dc6b727e49a2825557ad4e6ddf77915e to your computer and use it in GitHub Desktop.
This file contains hidden or 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
module Rescuable | |
extend ActiveSupport::Concern | |
module ClassMethods | |
def rescue_methods(*methods, from: nil, &block) | |
raise ArgumentError, 'Requires exception to rescue from' if from.blank? | |
from = [from] if !from.respond_to?(:any?) | |
methods.each do |method| | |
old_method = "_#{method}".to_sym | |
alias_method old_method, method | |
define_method method do |*args| | |
begin | |
send(old_method, *args) | |
rescue => e | |
if from.any? { |klass| e.is_a?(klass) } | |
return block.call(e) | |
else | |
raise e | |
end | |
end | |
end | |
end | |
end | |
end | |
end |
This file contains hidden or 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
require 'rescuable' | |
FailingClass.class_eval do | |
include Rescuable | |
rescue_methods :list, from: Redis::BaseConnectionError do |e| | |
report_error(e) | |
Set.new | |
end | |
rescue_methods :hash, from: Redis::BaseConnectionError do |e| | |
report_error(e) | |
{} | |
end | |
rescue_methods :add, :remove, :clear, :enable, :disable, from: Redis::BaseConnectionError do |e| | |
report_error(e) | |
true | |
end | |
def self.report_error(e) | |
Rails.logger.error e.message | |
Prometheus::Client.registry | |
.get(:errors) | |
.increment(error: e.class.name.camelcase) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment