-
Notifications
You must be signed in to change notification settings - Fork 32
/
Copy pathrescuing_exceptions.rb
97 lines (66 loc) · 1.74 KB
/
rescuing_exceptions.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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
require 'bundler/inline'
gemfile do
source 'https://rubygems.org'
gem 'u-case', '~> 4.1.0'
end
class DivideV1 < Micro::Case
attributes :a, :b
def call!
return Success result: { division: a / b } if a > 0 && b > 0
Failure result: { message: 'numbers must be greater than 0' }
rescue => e
Failure(e)
end
end
class DivideV2 < Micro::Case::Safe
attributes :a, :b
def call!
return Success result: { division: a / b } if a > 0 && b > 0
Failure result: { message: 'numbers must be greater than 0' }
end
end
#-------------------------#
puts "\n== DivideV1 ==\n"
#-------------------------#
#---------------------------------#
puts "\n-- Success scenario --\n\n"
#---------------------------------#
result = DivideV1.call(a: 4, b: 2)
p result.data if result.success?
#----------------------------------#
puts "\n-- Failure scenarios --\n\n"
#----------------------------------#
result = DivideV1.call(a: 4, b: 0)
p result.data if result.failure?
puts ''
result = DivideV1.call(a: -4, b: 2)
p result.data if result.failure?
#
# ---
#
#-------------------------#
puts "\n== DivideV2 ==\n"
#-------------------------#
#---------------------------------#
puts "\n-- Success scenario --\n\n"
#---------------------------------#
result = DivideV2.call(a: 4, b: 2)
puts result.value if result.success?
#----------------------------------#
puts "\n-- Failure scenarios --\n\n"
#----------------------------------#
result = DivideV2.call(a: 4, b: 0)
p result.value if result.failure?
puts ''
result = DivideV2.call(a: -4, b: 2)
p result.value if result.failure?
# :: example of the outputs ::
# -- Success scenario --
#
# 2
#
# -- Failure scenarios --
#
# #<ZeroDivisionError: divided by 0>
#
# numbers must be greater than 0