/
duplicate_rescue_exception.rb
60 lines (52 loc) · 1.35 KB
/
duplicate_rescue_exception.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
# frozen_string_literal: true
module RuboCop
module Cop
module Lint
# This cop checks that there are no repeated exceptions
# used in 'rescue' expressions.
#
# @example
# # bad
# begin
# something
# rescue FirstException
# handle_exception
# rescue FirstException
# handle_other_exception
# end
#
# # good
# begin
# something
# rescue FirstException
# handle_exception
# rescue SecondException
# handle_other_exception
# end
#
class DuplicateRescueException < Base
include RescueNode
MSG = 'Duplicate `rescue` exception detected.'
def on_rescue(node)
return if rescue_modifier?(node)
_body, *resbodies, _else = *node
resbodies.each_with_object(Set.new) do |resbody, previous|
rescued_exceptions = rescued_exceptions(resbody)
rescued_exceptions.each do |exception|
add_offense(exception) unless previous.add?(exception)
end
end
end
private
def rescued_exceptions(resbody)
rescue_group, = *resbody
if rescue_group
rescue_group.values
else
[]
end
end
end
end
end
end