Sha256: 450688fc04351a2c18daddb43f6cec88a648acc73d073c858558d72a8e6d6122

Contents?: true

Size: 1.25 KB

Versions: 7

Compression:

Stored size: 1.25 KB

Contents

# frozen_string_literal: true

require_relative 'main'
require_relative 'printing'

module CommandKit
  #
  # Adds exception handling and printing.
  #
  # ## Examples
  #
  #     include CommandKit::Main
  #     include CommandKit::ExceptionHandler
  #
  # ### Custom Exception Handling
  #
  #     include CommandKit::Main
  #     include CommandKit::ExceptionHandler
  #     
  #     def on_exception(error)
  #       print_error "error: #{error.message}"
  #       exit(1)
  #     end
  #
  module ExceptionHandler
    include Printing

    #
    # Calls superclass'es `#main` method, but rescues any uncaught exceptions
    # and passes them to {#on_exception}.
    #
    # @param [Array<String>] argv
    #   The given arguments Array.
    #
    # @return [Integer]
    #   The exit status of the command.
    #
    # @api public
    #
    def main(argv=[])
      super(argv)
    rescue Interrupt, Errno::EPIPE => error
      raise(error)
    rescue Exception => error
      on_exception(error)
    end

    #
    # Default method for handling when an exception is raised by `#main`.
    #
    # @param [Exception] error
    #   The raised exception.
    #
    # @api semipublic
    #
    def on_exception(error)
      print_exception(error)
      exit(1)
    end
  end
end

Version data entries

7 entries across 7 versions & 1 rubygems

Version Path
command_kit-0.6.0 lib/command_kit/exception_handler.rb
command_kit-0.5.6 lib/command_kit/exception_handler.rb
command_kit-0.5.5 lib/command_kit/exception_handler.rb
command_kit-0.5.4 lib/command_kit/exception_handler.rb
command_kit-0.5.3 lib/command_kit/exception_handler.rb
command_kit-0.5.2 lib/command_kit/exception_handler.rb
command_kit-0.5.1 lib/command_kit/exception_handler.rb