require 'error' module MyApp # Define the that MyApp has an `Error`. # This makes it very easy to see if an exception came from your application what-so-ever. # # This will define the `MyApp::Error` constant that is a `Class` that subclasses `::Error`. has_error # Define `Myapp::IntegerConversionError` class with a String (or anything responding to `to_s`). # # This will add constant `IntegerConversionError` that subclasses `MyApp::Error`. has_error 'IntegerConversionError' # Define with a Symbol (or anything responding to `to_sym`). # If the given Object does not respond to `to_s`, it then checks to see if it responds to # `to_sym`. If it does, it simply converts the Object to a Symbol, then to a String using `to_s`. # When you pass the `message` option, it will be returned when you call `Error#to_s`. # # Defines 'StringConversionError' that is a `Class` that subclasses `MyApp::Error`. has_error :string_conversion do |error| error.message { "`#@target` is not a String or does not respond to #to_s." } end # Define with a Hash (or anything responding to `to_h`). # Both the key and the value conform to the above rules. # # Defines 'InvalidEmailError' that is a `Class` that subclasses `MyApp::StringConversionError`. has_error 'invalid_email' => StringConversionError do |e| e.message { "email is not a valid email address." } end # Advanced usage. has_error invalid_gender: 'String Conversion' do |e| e.message { "#{@target || 'gender'} must be either `male` or `female`." } e.unless { "#{@target || 'gender'} must be either `male` or `female`." } end class User def initialize(name, email, age, gender) # Raise error in a normal fashion. # The argument must be a `Hash`, subclass of `Hash`, or respond to `to_hash`, ot `to_h`. # # All options passed to the `Hash` will be defined as instance variables on the instance of # the `Error` instance before the `message`, `if`, and `unless` `Proc`s are `instance_eval`'d # on the `Error` instance. raise StringConversionError, target: :name unless name.is_a?(String) || name.respond_to?(:string) raise InvalidEmailError, email: emai fail :invalid_gender, gender: gender end end end