Module: ExceptionCatchable

Defined in:
lib/exceptioncatchable.rb

Overview

Examples:

include ExceptionCatchable
p catch_exception(SyntaxError){raise SyntaxError} #=> #<SyntaxError: ...>
p rescue_exception(Exception){raise SyntaxError}  #=> #<SyntaxError: ...>
p rescue_exception{raise SyntaxError}             #=> #<SyntaxError: ...>

Defined Under Namespace

Classes: MismatchExceptionError

Instance Method Summary collapse

Instance Method Details

#catch_exception(kind, *kinds, &block) ⇒ void (private)

This method returns an undefined value.

catch targeted exceptions too strict

Yield Returns:

  • (Exception)

21
22
23
24
25
26
27
28
29
30
31
# File 'lib/exceptioncatchable.rb', line 21

def catch_exception(kind, *kinds, &block)
  ec = rescue_exception kind, *kinds, &block
  kinds = [kind, *kinds]
  
  unless kinds.any?{|k|ec.instance_of? k}
    raise MismatchExceptionError,
      "#{ec} is not instance of any target #{kinds}"
  end

  ec
end

#rescue_exception(kind = Exception, *kinds) ⇒ void (private)

This method returns an undefined value.

catch targeted exceptions and it's sub-exceptions

Yield Returns:

  • (Exception)

Raises:

  • (ArgumentError)

38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# File 'lib/exceptioncatchable.rb', line 38

def rescue_exception(kind=Exception, *kinds)
  raise ArgumentError, 'block was not given' unless block_given?
  kinds = [kind, *kinds]
  unless kinds.all?{|k|
    k.instance_of?(Class) and k.ancestors.include?(Exception)
  }
    raise TypeError, 'found not-Exception-class in arguments'
  end
  
  begin
    yield
  rescue Exception => ec
    if kinds.any?{|k|ec.kind_of? k}
      ec
    else
      raise MismatchExceptionError,
        "#{ec} is not kind of any target #{kinds}"
    end
  else
    raise 'can not catch exceptions'
  end
end