Exception: Clive::Error

Inherits:
StandardError
  • Object
show all
Defined in:
lib/clive/error.rb

Overview

For general errors with Clive. It stripts most of the backtrace which you don’t really want, and allows you to set nice error messages using Error.reason. Arguments can be passed and then used in messages by referencing with #n tokens, where n is the index of the argument.

A lot of this is pulled from OptionParser::ParseError see ruby-doc.org/stdlib/libdoc/optparse/rdoc/index.html.

Examples:


class MissingArgumentError < Error
  reason 'missing argument for #0'
end

raise MissingArgumentError.new(some_option)

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(*args) ⇒ Error

Returns a new instance of Error.

Parameters:

  • args

    Arguments that can be accessed with ‘#n’ in reason.



24
25
26
# File 'lib/clive/error.rb', line 24

def initialize(*args)
  @args = args
end

Instance Attribute Details

#argsObject

Returns the value of attribute args.



20
21
22
# File 'lib/clive/error.rb', line 20

def args
  @args
end

Class Method Details

._reasonObject

Accessor for the reason set with reason.



44
45
46
# File 'lib/clive/error.rb', line 44

def self._reason
  @reason
end

.filter_backtrace(array) ⇒ Object

Removes all references to files which are not the file being run unless in $DEBUG mode.



30
31
32
33
34
35
# File 'lib/clive/error.rb', line 30

def self.filter_backtrace(array)
  unless $DEBUG
    array = [$0]
  end
  array
end

.reason(str) ⇒ Object

Set the reason for the error class.

Parameters:



39
40
41
# File 'lib/clive/error.rb', line 39

def self.reason(str)
  @reason = str
end

Instance Method Details

#messageObject Also known as: to_s

Build the message by substituting the arguments into the reason.



53
54
55
56
57
58
59
60
61
62
# File 'lib/clive/error.rb', line 53

def message
  self.class._reason.gsub(/#\d/) do |i|
    arg = args[i[1].to_i]
    if arg.is_a?(Array)
      arg.map(&:to_s).to_s
    else
      arg.to_s
    end
  end
end

#set_backtrace(array) ⇒ Object



48
49
50
# File 'lib/clive/error.rb', line 48

def set_backtrace(array)
  super(self.class.filter_backtrace(array))
end