forked from rubocop/rubocop
/
rescue_standard_error.rb
128 lines (117 loc) · 3.17 KB
/
rescue_standard_error.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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
# frozen_string_literal: true
module RuboCop
module Cop
module Style
# This cop checks for rescuing `StandardError`. There are two supported
# styles `implicit` and `explicit`. This cop will not register an offense
# if any error other than `StandardError` is specified.
#
# @example EnforcedStyle: implicit
# # `implicit` will enforce using `rescue` instead of
# # `rescue StandardError`.
#
# # bad
# begin
# foo
# rescue StandardError
# bar
# end
#
# # good
# begin
# foo
# rescue
# bar
# end
#
# # good
# begin
# foo
# rescue OtherError
# bar
# end
#
# # good
# begin
# foo
# rescue StandardError, SecurityError
# bar
# end
#
# @example EnforcedStyle: explicit (default)
# # `explicit` will enforce using `rescue StandardError`
# # instead of `rescue`.
#
# # bad
# begin
# foo
# rescue
# bar
# end
#
# # good
# begin
# foo
# rescue StandardError
# bar
# end
#
# # good
# begin
# foo
# rescue OtherError
# bar
# end
#
# # good
# begin
# foo
# rescue StandardError, SecurityError
# bar
# end
class RescueStandardError < Base
include RescueNode
include ConfigurableEnforcedStyle
include RangeHelp
extend AutoCorrector
MSG_IMPLICIT = 'Omit the error class when rescuing ' \
'`StandardError` by itself.'
MSG_EXPLICIT = 'Avoid rescuing without specifying ' \
'an error class.'
def_node_matcher :rescue_without_error_class?, <<~PATTERN
(resbody nil? _ _)
PATTERN
def_node_matcher :rescue_standard_error?, <<~PATTERN
(resbody $(array (const {nil? cbase} :StandardError)) _ _)
PATTERN
def on_resbody(node)
return if rescue_modifier?(node)
case style
when :implicit
rescue_standard_error?(node) do |error|
offense_for_implicit_enforced_style(node, error)
end
when :explicit
rescue_without_error_class?(node) do
offense_for_exlicit_enforced_style(node)
end
end
end
private
def offense_for_implicit_enforced_style(node, error)
range = node.loc.keyword.join(error.loc.expression)
add_offense(range, message: MSG_IMPLICIT) do |corrector|
error = rescue_standard_error?(node)
range = range_between(node.loc.keyword.end_pos, error.loc.expression.end_pos)
corrector.remove(range)
end
end
def offense_for_exlicit_enforced_style(node)
add_offense(node.loc.keyword, message: MSG_EXPLICIT) do |corrector|
corrector.insert_after(node.loc.keyword, ' StandardError')
end
end
end
end
end
end