Module: Complain

Defined in:
lib/complain.rb,
lib/complain/version.rb

Overview

One-liner exception process

# replace
rescue => exc
  $stderr.puts exc.message
  $stderr.puts exc.backtrace
end
# with
rescue => exc
  Complain.(exc)
end

Constant Summary collapse

VERSION =
"1.0.1"

Class Method Summary collapse

Class Method Details

.call(exc, logger = :stderr, with_time: false, prefix: '', postfix: '', separator: "\n", skip_exc: false) ⇒ Object

Calls exception writer

Parameters:

  • exc (Exception)

    Exception to write.

  • logger (Mixed) (defaults to: :stderr)

    Logger - can be ‘:stderr`, `:stdout` or should respond to `error` or `puts`

  • [Boolean] (Hash)

    a customizable set of options



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
# File 'lib/complain.rb', line 26

def self.call(exc,
              logger = :stderr,
              with_time: false,
              prefix: '',
              postfix: '',
              separator: "\n",
              skip_exc: false)

  message = if exc.is_a?(Exception)
              [exc.message, exc.backtrace.join(separator)]
            elsif exc.is_a?(String)
              [exc]
            elsif exc.respond_to?(:to_s)
              [exc.to_s]
            elsif exc.respond_to?(:inspect)
              [exc.inspect]
            else
              ["Message can't be processed at #{caller.join(separator)}"]
            end

  message.unshift(Time.now.to_s) if with_time
  message = message.join(separator)
  message = prefix + message + postfix

  if logger.nil? || :stderr == logger
    $stderr.puts message
  elsif :stdout == logger
    $stdout.puts message
  elsif :exception == logger
    skip_exc = true
    raise exc
  elsif logger.respond_to?(:error)
    logger.error message
  elsif logger.respond_to?(:puts)
    logger.puts message
  else
    skip_exc = true
    Complain.("Can't write to logs:\n" + message, :exception, skip_exc: true)
  end
rescue => exc
  if skip_exc
    raise exc
  else
    Complain.(exc, skip_exc: true)
  end
end