Class: Console::Error

Inherits:
Generic show all
Defined in:
lib/console/error.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(exception, root = nil) ⇒ Error

Returns a new instance of Error.



35
36
37
38
# File 'lib/console/error.rb', line 35

def initialize(exception, root = nil)
  @exception = exception
  @root = root
end

Instance Attribute Details

#exceptionObject (readonly)

Returns the value of attribute exception.



40
41
42
# File 'lib/console/error.rb', line 40

def exception
  @exception
end

#rootObject (readonly)

Returns the value of attribute root.



41
42
43
# File 'lib/console/error.rb', line 41

def root
  @root
end

Class Method Details

.current_working_directoryObject



25
26
27
28
29
# File 'lib/console/error.rb', line 25

def self.current_working_directory
  Dir.getwd
rescue # e.g. Errno::EMFILE
  nil
end

.for(exception) ⇒ Object



31
32
33
# File 'lib/console/error.rb', line 31

def self.for(exception)
  self.new(exception, self.current_working_directory)
end

.register(terminal) ⇒ Object



43
44
45
46
47
# File 'lib/console/error.rb', line 43

def self.register(terminal)
  terminal[:exception_title] ||= terminal.style(:red, nil, :bold)
  terminal[:exception_detail] ||= terminal.style(:yellow)
  terminal[:exception_backtrace] ||= terminal.style(:red)
end

Instance Method Details

#format(output, terminal, verbose) ⇒ Object



49
50
51
# File 'lib/console/error.rb', line 49

def format(output, terminal, verbose)
  format_exception(@exception, nil, output, terminal, verbose)
end

#format_exception(exception, prefix = nil, output, terminal, verbose) ⇒ Object



53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
# File 'lib/console/error.rb', line 53

def format_exception(exception, prefix = nil, output, terminal, verbose)
  lines = exception.message.lines.map(&:chomp)
  
  output.puts "  #{prefix}#{terminal[:exception_title]}#{exception.class}#{terminal.reset}: #{lines.shift}"
  
  lines.each do |line|
    output.puts "  #{terminal[:exception_detail]}#{line}#{terminal.reset}"
  end
  
  exception.backtrace&.each_with_index do |line, index|
    path, offset, message = line.split(":")
    
    # Make the path a bit more readable
    path.gsub!(/^#{@root}\//, "./") if @root
    
    output.puts "  #{index == 0 ? "→" : " "} #{terminal[:exception_backtrace]}#{path}:#{offset}#{terminal.reset} #{message}"
  end
  
  if exception.cause and verbose
    format_exception(exception.cause, "Caused by ", output, terminal)
  end
end