Created
January 1, 2014 08:13
-
-
Save myronmarston/8206122 to your computer and use it in GitHub Desktop.
message_specific_error_classifier.rb
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
# Generates a module that can be used in a rescue clause | |
# in order to rescue errors that match a specific class | |
# and message. This is useful when there is a generic | |
# error like `Sequel::Mysql2Error` that we want to only rescue | |
# some instances of based on the message. | |
module MessageSpecificErrorClassifier | |
def self.new(root_error, fragment) | |
Module.new do | |
define_singleton_method(:fragment) { fragment } | |
define_singleton_method(:root_error) { root_error } | |
define_singleton_method :=== do |raised_error| | |
root_error === raised_error && raised_error.message.include?(fragment) | |
end | |
end | |
end | |
end | |
DBExists = MessageSpecificErrorClassifier.new( | |
Sequel::DatabaseError, "database exists" | |
) | |
DBDoesNotExist = MessageSpecificErrorClassifier.new( | |
Sequel::DatabaseError, "database doesn't exist" | |
) | |
UnknownDB = MessageSpecificErrorClassifier.new( | |
Sequel::DatabaseError, "Mysql2::Error: Unknown database" | |
) | |
def do_something | |
foobar | |
rescue UnknownDB | |
handle_it_somehow | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment