diff options
author | GitLab Bot <gitlab-bot@gitlab.com> | 2023-06-20 00:10:01 +0300 |
---|---|---|
committer | GitLab Bot <gitlab-bot@gitlab.com> | 2023-06-20 00:10:01 +0300 |
commit | 7361375554b55ca52e0282bbe6cd063e2848bc2b (patch) | |
tree | 17a82da8e5ecd722da643554d521900d7e60f29b /rubocop | |
parent | 2f00709f337c76982dfe69cbc62dc3cb148131f2 (diff) |
Add latest changes from gitlab-org/gitlab@master
Diffstat (limited to 'rubocop')
-rw-r--r-- | rubocop/cop/background_migration/avoid_silent_rescue_exceptions.rb | 84 |
1 files changed, 84 insertions, 0 deletions
diff --git a/rubocop/cop/background_migration/avoid_silent_rescue_exceptions.rb b/rubocop/cop/background_migration/avoid_silent_rescue_exceptions.rb new file mode 100644 index 00000000000..0bd5c587205 --- /dev/null +++ b/rubocop/cop/background_migration/avoid_silent_rescue_exceptions.rb @@ -0,0 +1,84 @@ +# frozen_string_literal: true + +module RuboCop + module Cop + module BackgroundMigration + # Checks for rescuing errors inside Batched Background Migration Job Classes. + # + # @example + # + # # bad + # def perform + # do_something + # rescue StandardError => error + # logger.error(error.message) + # end + # + # # bad + # def perform + # do_something + # rescue JSON::ParserError, ActiveRecord::StatementTimeout => error + # logger.error(error.message) + # end + # + # # good + # def perform + # do_something + # rescue StandardError => error + # logger.error(error.message) + # + # raise + # end + # + # # good + # def perform + # do_something + # rescue JSON::ParserError, ActiveRecord::StatementTimeout => error + # logger.error(error.message) + # + # raise MyCustomException + # end + class AvoidSilentRescueExceptions < RuboCop::Cop::Base + MSG = 'Avoid rescuing exceptions inside job classes. See ' \ + 'https://docs.gitlab.com/ee/development/database/batched_background_migrations.html#best-practices' + + def_node_matcher :batched_migration_job_class?, <<~PATTERN + (class + const + (const {nil? cbase const} :BatchedMigrationJob) + ... + ) + PATTERN + + # Matches rescued exceptions that were not re-raised + # + # @example + # rescue => error + # rescue Exception => error + # rescue JSON::ParserError => e + # rescue ActiveRecord::StatementTimeout => error + # rescue ActiveRecord::StatementTimeout, ActiveRecord::QueryCanceled => error + def_node_matcher :rescue_timeout_error, <<~PATTERN + (resbody $_ _ (... !(send nil? :raise ...))) + PATTERN + + def on_class(node) + @batched_migration_job_class ||= batched_migration_job_class?(node) + end + + def on_resbody(node) + return unless batched_migration_job_class + + rescue_timeout_error(node) do |error| + range = error ? node.loc.keyword.join(error.loc.expression) : node.loc.keyword + add_offense(range) + end + end + + private + + attr_reader :batched_migration_job_class + end + end + end +end |