Is there a best practice for defining custom error types in a Ruby library (gem) or Ruby on Rails application? Specifically:
This is an old question, but I wanted to share how I'm handling custom errors in Rails, including attaching error messages, testing, and how to handle this with ActiveRecord models.
class MyClass
# create a custome error
class MissingRequirement < StandardError; end
def my_instance_method
raise MyClass::MissingRequirement, "My error msg" unless true
end
end
test "should raise MissingRequirement if ____ is missing"
# should raise an error
error = assert_raises(MyClass::MissingRequirement) {
MyClass.new.my_instance_method
}
assert error.message = "My error msg"
end
I think it's worth noting that if working with an ActiveRecord model, a popular pattern is to add an error to the model as described below, so that your validations will fail:
def MyModel < ActiveRecord::Base
validate :code_does_not_contain_hyphens
def code_does_not_contain_hyphens
errors.add(:code, "cannot contain hyphens") if code.include?("-")
end
end
When validations are run, this method will piggy-back onto ActiveRecord's ActiveRecord::RecordInvalid error class and will cause validations to fail.
Hope this helps!