Sha256: f021653183f8666742a0b744022d9b2844e70dd3fbc048f0db5322df779c1c20

Contents?: true

Size: 1.52 KB

Versions: 3

Compression:

Stored size: 1.52 KB

Contents

# encoding: utf-8

module ServiceObjects

  module Helpers

    # Features for escaping from runtime errors
    #
    # @note
    #   A target class should **include** the module
    module Exceptions

      # Re-raises standard errors as <tt>ServiceObjects::Invalid</tt>
      #
      # Mutates the current object by adding error messages
      #
      # @example
      #   class MyClass
      #     includes ServiceObjects::Helpers::Exceptions
      #   end
      #
      #   begin
      #     MyClass.new.escape { fail StandardError.new "foo" }
      #   rescue => err
      #     puts err.class.name
      #     puts messages
      #   end
      #
      #   # => ServiceObjects::Invalid
      #   # => [<ServiceObject::Message type="error" text="foo" ...>]
      #
      # @yield  the block
      #
      # @raise  [ServiceObjects::Invalid]
      #   if the block raises +StandardError+
      #
      # @return [Object] the value returned by the block
      def escape
        yield if block_given?
      rescue => error
        collect_messages_from error
        raise Invalid.new(self)
      end

      private

      # @!parse include ServiceObjects::Helpers::Messages
      def self.included(klass)
        klass.include Messages
      end

      def collect_messages_from(error)
        if error.is_a? Invalid
          messages.concat(error.messages) if error.object != self
        else
          add_message type: "error", text: error.message
        end
      end

    end # module Exceptions

  end # module Helpers

end # module ServiceObjects

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
service_objects-0.1.0 lib/service_objects/helpers/exceptions.rb
service_objects-0.0.2 lib/service_objects/helpers/exceptions.rb
service_objects-0.0.1 lib/service_objects/helpers/exceptions.rb