Class: Morpheus::Cli::ErrorHandler

Inherits:
Object
  • Object
show all
Includes:
Term::ANSIColor
Defined in:
lib/morpheus/cli/error_handler.rb

Instance Method Summary collapse

Constructor Details

#initialize(io = $stderr) ⇒ ErrorHandler

Returns a new instance of ErrorHandler.



13
14
15
# File 'lib/morpheus/cli/error_handler.rb', line 13

def initialize(io=$stderr)
  @stderr = io
end

Instance Method Details

#handle_error(err, options = {}) ⇒ Object



17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
# File 'lib/morpheus/cli/error_handler.rb', line 17

def handle_error(err, options={})
  exit_code = 1
  options = (options || {}).clone
  if Morpheus::Logging.debug?
    options[:debug] = true
  end
  do_print_stacktrace = true
  
  #@stderr.puts "#{dark}Handling error #{err.class} - #{err}#{reset}"

  case (err)
  # when Morpheus::Cli::CommandNotFoundError
  #   puts_angry_error err.message
  #   @stderr.puts "Try help to see a list of available commands"
  #   do_print_stacktrace = false
  #   if err.exit_code
  #     exit_code = err.exit_code
  #   end
  when ::OptionParser::InvalidOption, ::OptionParser::AmbiguousOption, 
      ::OptionParser::MissingArgument, ::OptionParser::InvalidArgument, 
      ::OptionParser::NeedlessArgument
    # raise err
    # @stderr.puts "#{red}#{err.message}#{reset}"
    puts_angry_error err.message
    @stderr.puts err.optparse.banner if err.optparse && err.optparse.banner
    @stderr.puts "Try --help for more usage information"
    do_print_stacktrace = false
    # exit_code = 127
  when Morpheus::Cli::CommandArgumentsError
    puts_angry_error err.message
    if err.args.include?("--help") || err.args.include?("--help")
      @stderr.puts err.optparse
    else
      @stderr.puts err.optparse.banner if err.optparse && err.optparse.banner
      @stderr.puts "Try --help for more usage information"
    end
    
    do_print_stacktrace = false
    if err.exit_code
      exit_code = err.exit_code
    end

  when Morpheus::Cli::CommandError
    # this should probably always print the whole thing as red, but just does the first line for now.
    # until verify_args! replaces raise_command_error where the full parser help is in the error message..
    message_lines = err.message.split(/\r?\n/)
    first_line = message_lines.shift
    puts_angry_error first_line
    if !message_lines.empty?
      @stderr.puts message_lines.join("\n") unless message_lines.empty?
    else
      if err.args.include?("--help") || err.args.include?("--help")
        @stderr.puts err.optparse
      else
        @stderr.puts err.optparse.banner if err.optparse && err.optparse.banner && message_lines.empty?
        @stderr.puts "Try --help for more usage information"
      end
    end
    do_print_stacktrace = false
    if err.exit_code
      exit_code = err.exit_code
    end
  when Morpheus::Cli::ExpressionParser::InvalidExpression
    # @stderr.puts "#{red}#{err.message}#{reset}"
    puts_angry_error err.message
    do_print_stacktrace = false
    exit_code = 99
  when SocketError
    @stderr.puts "#{red}Error Communicating with the remote appliance.#{reset}"
    @stderr.puts "#{red}#{err.message}#{reset}"
  when RestClient::Exceptions::Timeout
    @stderr.puts "#{red}Error Communicating with the remote appliance.#{reset}"
    @stderr.puts "#{red}#{err.message}#{reset}"
  when Errno::ECONNREFUSED
    @stderr.puts "#{red}Error Communicating with the remote appliance.#{reset}"
    @stderr.puts "#{red}#{err.message}#{reset}"
  when OpenSSL::SSL::SSLError
    @stderr.puts "#{red}Error Communicating with the remote appliance.#{reset}"
    @stderr.puts "#{red}#{err.message}#{reset}"
  when RestClient::Exception
    print_rest_exception(err, options)
    # no stacktrace for now...
    return exit_code, err
  when ArgumentError
    @stderr.puts "#{red}Argument Error: #{err.message}#{reset}"
  else
    @stderr.puts "#{red}Unexpected Error#{reset}"
  end

  if do_print_stacktrace
    if options[:debug]
      if err.is_a?(Exception)
        print_stacktrace(err)
      else
        @stderr.puts err.to_s
      end
    else
      @stderr.puts "Use -V or --debug for more verbose debugging information."
    end
  end

  return exit_code, err

end


190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
# File 'lib/morpheus/cli/error_handler.rb', line 190

def print_rest_errors(response, options={})
  begin
    if options[:json]
      @stderr.print red
      @stderr.print JSON.pretty_generate(response)
      @stderr.print reset, "\n"
    else
      if !response['success']
        @stderr.print red,bold
        if response['msg']
          @stderr.puts response['msg']
        end
        if response['errors']
          response['errors'].each do |key, value|
            @stderr.print "* #{key}: #{value}\n"
          end
        end
        @stderr.print reset
      else
        # this should not really happen
        @stderr.print cyan,bold, "\nSuccess!"
      end
    end
  ensure
    @stderr.print reset
  end
end


135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
# File 'lib/morpheus/cli/error_handler.rb', line 135

def print_rest_exception(err, options)
  e = err
  # heh
  if Morpheus::Logging.debug? && options[:debug].nil?
    options[:debug] = true
  end
  if err.response
    if options[:debug]
      begin
        print_rest_exception_request_and_response(e)
      ensure
        @stderr.print reset
      end
      return
    end
    if err.response.code == 400
      begin
        print_rest_errors(JSON.parse(err.response.to_s), options)
      rescue TypeError, JSON::ParserError => ex
      end
    elsif err.response.code == 404
      begin
        print_rest_errors(JSON.parse(err.response.to_s), options)
      rescue TypeError, JSON::ParserError => ex
        # not json, just 404
        @stderr.print red, "Error Communicating with the remote appliance. #{e}", reset, "\n"  
      end
    else
      @stderr.print red, "Error Communicating with the remote appliance. #{e}", reset, "\n"
      if options[:json] || options[:debug]
        begin
          response = JSON.parse(e.response.to_s)
          # @stderr.print red
          @stderr.print JSON.pretty_generate(response)
          @stderr.print reset, "\n"
        rescue TypeError, JSON::ParserError => ex
          @stderr.print red, "Failed to parse JSON response: #{ex}", reset, "\n"
          # @stderr.print red
          @stderr.print response.to_s
          @stderr.print reset, "\n"
        ensure
          @stderr.print reset
        end
      else
        @stderr.puts "Use -V or --debug for more verbose debugging information."
      end
    end
  else
    @stderr.print red, "Error Communicating with the remote appliance. #{e}", reset, "\n"
  end
  # uh, having this print method return exit_code, err to standardize return values of methods that are still calling it, at the end just by chance..
  # return exit_code, err
  return 1, err
end


241
242
243
244
245
246
247
248
249
250
# File 'lib/morpheus/cli/error_handler.rb', line 241

def print_rest_exception_request_and_response(e)
  @stderr.puts "#{red}Error Communicating with the remote appliance. (HTTP #{e.response.code})#{reset}"
  response = e.response
  request = response.instance_variable_get("@request")
  @stderr.print red
  print_rest_request(request)
  @stderr.print "\n"
  print_rest_response(response)
  @stderr.print reset
end


218
219
220
221
222
223
# File 'lib/morpheus/cli/error_handler.rb', line 218

def print_rest_request(req)
  @stderr.print "REQUEST"
  @stderr.print "\n"
  @stderr.print "#{req.method.to_s.upcase} #{req.url.inspect}"
  @stderr.print "\n"
end


225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
# File 'lib/morpheus/cli/error_handler.rb', line 225

def print_rest_response(res)
  # size = @raw_response ? File.size(@tf.path) : (res.body.nil? ? 0 : res.body.size)
  size = (res.body.nil? ? 0 : res.body.size)
  @stderr.print "RESPONSE"
  @stderr.print "\n"
  display_size = Filesize.from("#{size} B").pretty rescue size
  @stderr.print "HTTP #{res.net_http_res.code} #{res.net_http_res.message} | #{(res['Content-type'] || '').gsub(/;.*$/, '')} #{display_size}"
  @stderr.print "\n"
  begin
    @stderr.print JSON.pretty_generate(JSON.parse(res.body))
  rescue
    @stderr.print res.body.to_s
  end
  @stderr.print "\n"
end


122
123
124
125
# File 'lib/morpheus/cli/error_handler.rb', line 122

def print_stacktrace(err)
  @stderr.print red, "\n", "#{err.class}: #{err.message}", "\n", reset
  @stderr.print err.backtrace.join("\n"), "\n\n"
end