Skip to content

Instantly share code, notes, and snippets.

@myronmarston
Created January 1, 2014 08:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save myronmarston/8206122 to your computer and use it in GitHub Desktop.
Save myronmarston/8206122 to your computer and use it in GitHub Desktop.
message_specific_error_classifier.rb
# 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