RuboCop: Naming/RescuedExceptionsVariableName

[skip-stages=Flakey]

auto-corrected

Change-Id: Ie73290f10e1b9dbdd32d47513de0ce1b661c9199
Reviewed-on: https://gerrit.instructure.com/c/canvas-lms/+/278625
Tested-by: Service Cloud Jenkins <svc.cloudjenkins@instructure.com>
Reviewed-by: Jacob Burroughs <jburroughs@instructure.com>
QA-Review: Cody Cutrer <cody@instructure.com>
Product-Review: Cody Cutrer <cody@instructure.com>
This commit is contained in:
Cody Cutrer 2021-11-17 13:34:10 -07:00
parent 872e5458af
commit 0b8f78ffd0
33 changed files with 93 additions and 91 deletions

View File

@ -75,6 +75,8 @@ Naming/HeredocDelimiterNaming:
Naming/FileName:
Exclude:
- "**/Gemfile.d/~after.rb"
Naming/RescuedExceptionsVariableName:
Severity: error
Performance:
Severity: error

View File

@ -587,12 +587,12 @@ class CalendarEventsApiController < ApplicationController
cancel_existing: value_to_boolean(params[:cancel_existing]),
comments: params['comments'])
render :json => event_json(reservation, @current_user, session)
rescue CalendarEvent::ReservationError => err
rescue CalendarEvent::ReservationError => e
reservations = participant ? @event.appointment_group.reservations_for(participant) : []
render :json => [{
:attribute => 'reservation',
:type => 'calendar_event',
:message => err.message,
:message => e.message,
:reservations => reservations.map { |r| event_json(r, @current_user, session) }
}],
:status => :bad_request

View File

@ -233,8 +233,8 @@ class CollaborationsController < ApplicationController
flash[:error] = t 'errors.cannot_load_collaboration', "Cannot load collaboration"
redirect_to named_context_url(@context, :context_collaborations_url)
end
rescue GoogleDrive::ConnectionException => drive_exception
Canvas::Errors.capture(drive_exception, {}, :warn)
rescue GoogleDrive::ConnectionException => e
Canvas::Errors.capture(e, {}, :warn)
flash[:error] = t 'errors.cannot_load_collaboration', "Cannot load collaboration"
redirect_to named_context_url(@context, :context_collaborations_url)
end
@ -336,13 +336,13 @@ class CollaborationsController < ApplicationController
format.json { render :json => @collaboration.errors, :status => :bad_request }
end
end
rescue GoogleDrive::ConnectionException => error
Rails.logger.warn error
rescue GoogleDrive::ConnectionException => e
Rails.logger.warn e
flash[:error] = t 'errors.update_failed', "Collaboration update failed" # generic failure message
if error.message.include?('File not found')
if e.message.include?('File not found')
flash[:error] = t 'google_drive.file_not_found', "Collaboration file not found"
end
raise error unless error.message.include?('File not found')
raise e unless e.message.include?('File not found')
redirect_to named_context_url(@context, :context_collaborations_url)
end

View File

@ -453,10 +453,10 @@ class ConversationsController < ApplicationController
render :json => [conversation_json(@conversation.reload, @current_user, session, :include_indirect_participants => true, :messages => [message])], :status => :created
end
end
rescue ActiveRecord::RecordInvalid => err
render :json => err.record.errors, :status => :bad_request
rescue ConversationsHelper::InvalidContextError => err
render json: { message: err.message }, status: :bad_request
rescue ActiveRecord::RecordInvalid => e
render :json => e.record.errors, :status => :bad_request
rescue ConversationsHelper::InvalidContextError => e
render json: { message: e.message }, status: :bad_request
end
# @API Get running batches

View File

@ -217,8 +217,8 @@ class CustomDataController < ApplicationController
saved = cd.lock_and_save do
overwrite = cd.set_data(@scope, data)
end
rescue CustomData::WriteConflict => wc
render(json: wc.as_json.merge(message: wc.message), status: :conflict) and return
rescue CustomData::WriteConflict => e
render(json: e.as_json.merge(message: e.message), status: :conflict) and return
end
if saved

View File

@ -957,10 +957,10 @@ class FilesController < ApplicationController
begin
homework_service.submit(params[:eula_agreement_timestamp], params[:comment])
homework_service.success!
rescue => error
error_id = Canvas::Errors.capture_exception(self.class.name, error)[:error_report]
rescue => e
error_id = Canvas::Errors.capture_exception(self.class.name, e)[:error_report]
message = "Unexpected error, ID: #{error_id || 'unknown'}"
logger.error "Error submitting a file: #{error} - #{error.backtrace}"
logger.error "Error submitting a file: #{e} - #{e.backtrace}"
homework_service.failed!(message)
end
elsif progress.running?

View File

@ -164,10 +164,10 @@ class GradeChangeAuditApiController < AuditorApiController
def for_course
begin
course = Course.find(params[:course_id])
rescue ActiveRecord::RecordNotFound => not_found
rescue ActiveRecord::RecordNotFound => e
return render_unauthorized_action unless admin_authorized?
raise not_found
raise e
end
return render_unauthorized_action unless course_authorized?(course)
@ -294,10 +294,10 @@ class GradeChangeAuditApiController < AuditorApiController
def for_course_and_other_parameters
begin
course = Course.find(params[:course_id])
rescue ActiveRecord::RecordNotFound => not_found
rescue ActiveRecord::RecordNotFound => e
return render_unauthorized_action unless admin_authorized?
raise not_found
raise e
end
return render_unauthorized_action unless course_authorized?(course)

View File

@ -195,9 +195,9 @@ module Lti::IMS
json[Lti::Result::AGS_EXT_SUBMISSION] = { content_items: content_items }
rescue Net::ReadTimeout, CanvasHttp::CircuitBreakerError
return render_error('failed to communicate with file service', :gateway_timeout)
rescue CanvasHttp::InvalidResponseCodeError => err
err_message = "uploading to file service failed with #{err.code}: #{err.body}"
return render_error(err_message, :bad_request) if err.code == 400
rescue CanvasHttp::InvalidResponseCodeError => e
err_message = "uploading to file service failed with #{e.code}: #{e.body}"
return render_error(err_message, :bad_request) if e.code == 400
# 5xx and other unexpected errors
return render_error(err_message, :internal_server_error)

View File

@ -561,8 +561,8 @@ class OutcomeGroupsApiController < ApplicationController
begin
@outcome_link.destroy
render :json => outcome_link_json(@outcome_link, @current_user, session)
rescue ContentTag::LastLinkToOutcomeNotDestroyed => error
render :json => { 'message' => error.message }, :status => :bad_request
rescue ContentTag::LastLinkToOutcomeNotDestroyed => e
render :json => { 'message' => e.message }, :status => :bad_request
rescue ActiveRecord::RecordNotSaved
render :json => 'error'.to_json, :status => :bad_request
end

View File

@ -400,10 +400,10 @@ class Quizzes::QuizQuestionsController < ApplicationController
def guard_against_big_fields
yield
rescue Quizzes::QuizQuestion::RawFields::FieldTooLongError => ex
raise ex unless request.xhr?
rescue Quizzes::QuizQuestion::RawFields::FieldTooLongError => e
raise e unless request.xhr?
render_xhr_exception(ex, ex.message)
render_xhr_exception(e, e.message)
end
def require_question

View File

@ -180,9 +180,9 @@ class RubricAssessmentsController < ApplicationController
render json: json
end
rescue Assignment::GradeError => error
json = { errors: { base: error.to_s, error_code: error.error_code } }
render json: json, status: error.status_code || :bad_request
rescue Assignment::GradeError => e
json = { errors: { base: e.to_s, error_code: e.error_code } }
render json: json, status: e.status_code || :bad_request
end
end
end

View File

@ -139,8 +139,8 @@ class Mutations::CreateSubmission < Mutations::BaseMutation
{ submission: submission }
rescue ActiveRecord::RecordNotFound
raise GraphQL::ExecutionError, 'not found'
rescue ActiveRecord::RecordInvalid => invalid
errors_for(invalid.record)
rescue ActiveRecord::RecordInvalid => e
errors_for(e.record)
end
private

View File

@ -67,8 +67,8 @@ class Mutations::CreateSubmissionComment < Mutations::BaseMutation
comment = assignment.add_submission_comment(submission.user, opts).first
comment.mark_read!(current_user)
{ submission_comment: comment }
rescue ActiveRecord::RecordInvalid => invalid
errors_for(invalid.record)
rescue ActiveRecord::RecordInvalid => e
errors_for(e.record)
rescue ActiveRecord::RecordNotFound
raise GraphQL::ExecutionError, 'not found'
end

View File

@ -91,7 +91,7 @@ class Mutations::CreateSubmissionDraft < Mutations::BaseMutation
{ submission_draft: submission_draft }
rescue ActiveRecord::RecordNotFound
raise GraphQL::ExecutionError, 'not found'
rescue ActiveRecord::RecordInvalid => invalid
rescue ActiveRecord::RecordInvalid => e
# activerecord validation is not robust to race condition
# multiple concurrent requests may penetrate activerecord validations
# and save dup records for a combination of submission_id and attempt
@ -109,7 +109,7 @@ class Mutations::CreateSubmissionDraft < Mutations::BaseMutation
retry
end
end
errors_for(invalid.record)
errors_for(e.record)
rescue SubmissionError => e
validation_error(e.message)
end

View File

@ -39,8 +39,8 @@ class Mutations::MarkSubmissionCommentsRead < Mutations::BaseMutation
ViewedSubmissionComment.create!(submission_comment_id: sc_id, user: current_user)
end
{ submission_comments: SubmissionComment.where(id: input_sc_ids) }
rescue ActiveRecord::RecordInvalid => invalid
errors_for(invalid.record)
rescue ActiveRecord::RecordInvalid => e
errors_for(e.record)
rescue ActiveRecord::RecordNotFound
raise GraphQL::ExecutionError, 'not found'
end

View File

@ -97,10 +97,10 @@ class Mutations::UpdateNotificationPreferences < Mutations::BaseMutation
}
rescue ActiveRecord::RecordNotFound
raise GraphQL::ExecutionError, 'not found'
rescue ActiveRecord::RecordInvalid => invalid
errors_for(invalid.record)
rescue ::Mutations::UpdateNotificationPreferences::ValidationError => error
validation_error(error.message)
rescue ActiveRecord::RecordInvalid => e
errors_for(e.record)
rescue ::Mutations::UpdateNotificationPreferences::ValidationError => e
validation_error(e.message)
end
def validate_input(input)

View File

@ -52,8 +52,8 @@ module IncomingMail
})
true
end
rescue IncomingMail::Errors::ReplyFrom => error
bounce_message(original_message, incoming_message, error, outgoing_from_address, from_channel)
rescue IncomingMail::Errors::ReplyFrom => e
bounce_message(original_message, incoming_message, e, outgoing_from_address, from_channel)
rescue => e
Canvas::Errors.capture_exception("IncomingMailProcessor", e)
end

View File

@ -206,9 +206,9 @@ module CanvasRails
raise "Canvas requires PostgreSQL 12 or newer" unless postgresql_version >= 12_00_00
break
rescue ::PG::Error => error
if error.message.include?("does not exist")
raise ActiveRecord::NoDatabaseError.new(error.message)
rescue ::PG::Error => e
if e.message.include?("does not exist")
raise ActiveRecord::NoDatabaseError.new(e.message)
elsif index == hosts.length - 1
raise
end

View File

@ -42,11 +42,11 @@ callback_chain.append(cb) if cb
module IgnoreSlaveErrors
def save_record(alternate_record = nil)
super
rescue ActiveRecord::StatementInvalid => error
rescue ActiveRecord::StatementInvalid => e
# "simulated" secondary of a user with read-only access; probably the same error for Slony
raise if !error.message.match(/PG(?:::)?Error: ERROR: +permission denied for relation/) &&
raise if !e.message.match(/PG(?:::)?Error: ERROR: +permission denied for relation/) &&
# real secondary that's in recovery
!error.message.match(/PG(?:::)?Error: ERROR: +cannot execute UPDATE in a read-only transaction/)
!e.message.match(/PG(?:::)?Error: ERROR: +cannot execute UPDATE in a read-only transaction/)
end
end
Authlogic::Session::Base.prepend(IgnoreSlaveErrors)

View File

@ -54,8 +54,8 @@ module EventStream::Backend
send(operation, record)
stream.run_callbacks(operation, record)
rescue => exception
stream.run_callbacks(:error, operation, record, exception)
rescue => e
stream.run_callbacks(:error, operation, record, e)
raise if stream.raise_on_error
end

View File

@ -84,8 +84,8 @@ module EventStream::Backend
stream.database.send(:"#{operation}_record", stream.table, { stream.id_column => record.id }, stream.operation_payload(operation, record), ttl_seconds)
stream.run_callbacks(operation, record)
end
rescue => exception
stream.run_callbacks(:error, operation, record, exception)
rescue => e
stream.run_callbacks(:error, operation, record, e)
raise if stream.raise_on_error
end

View File

@ -64,9 +64,9 @@ module Canvas
result = dynamodb.create_table(params)
Rails.logger.debug('Created table. Status: ' + result.table_description.table_status)
true
rescue Aws::DynamoDB::Errors::ServiceError => error
rescue Aws::DynamoDB::Errors::ServiceError => e
Rails.logger.debug('Unable to create table:')
Rails.logger.debug(error.message)
Rails.logger.debug(e.message)
false
end
end

View File

@ -67,8 +67,8 @@ module Canvas
entry << "\n#{e.class}"
begin
entry << " (#{e.message}):" if e.respond_to?(:message)
rescue => new_err
entry << "\n***[WARNING]: Unable to extract error message due to #{new_err}"
rescue => e
entry << "\n***[WARNING]: Unable to extract error message due to #{e}"
end
entry << "\n"
entry << e.annoted_source_code.to_s if e.respond_to?(:annoted_source_code)

View File

@ -54,8 +54,8 @@ module Canvas::Vault
LocalCache.write(cache_key, cached_data, expires_in: cache_ttl)
end
cached_data
rescue => exception
Canvas::Errors.capture_exception(:vault, exception)
rescue => e
Canvas::Errors.capture_exception(:vault, e)
stale_value = LocalCache.fetch_without_expiration(CACHE_KEY_PREFIX + path)
return stale_value if stale_value.present?

View File

@ -132,16 +132,16 @@ module MicrosoftSync
result
rescue ExpectedErrorWrapper => e
raise e.wrapped_exception
rescue => error
response_code = response&.code&.to_s || error.class.name.tr(':', '_')
rescue => e
response_code = response&.code&.to_s || e.class.name.tr(':', '_')
if intermittent_non_throttled?(error) && retries > 0
if intermittent_non_throttled?(e) && retries > 0
retries -= 1
log_and_increment(method, path, statsd_tags, :retried, response_code)
retry
end
log_and_increment(method, path, statsd_tags, statsd_name_for_error(error), response_code)
log_and_increment(method, path, statsd_tags, statsd_name_for_error(e), response_code)
raise
end

View File

@ -32,8 +32,8 @@ module Services
# TODO: remove this once we teach the rcs to consume the asymmetric ones
symmetric: true
)
rescue Canvas::Security::InvalidJwtKey => exception
Canvas::Errors.capture_exception(:jwt, exception)
rescue Canvas::Security::InvalidJwtKey => e
Canvas::Errors.capture_exception(:jwt, e)
env_hash[:JWT] = "InvalidJwtKey"
end
end

View File

@ -54,8 +54,8 @@ module Services
raise(CloneUrlError, attachment.upload_error_message) if attachment.file_state == 'errored'
progress.complete! unless progress.failed?
rescue => error
mark_as_failure(error)
rescue => e
mark_as_failure(e)
end
def on_permanent_failure(error)
@ -95,8 +95,8 @@ module Services
homework_service.submit(eula_agreement_timestamp, comment)
homework_service.success!
rescue => error
mark_as_failure(error)
rescue => e
mark_as_failure(e)
end
def on_permanent_failure(error)

View File

@ -35,9 +35,9 @@ module SupportHelpers
fix # actually do it
notify "Success", success_message
rescue => error
notify "Error", error_message(error)
raise error
rescue => e
notify "Error", error_message(e)
raise e
end
def fix

View File

@ -419,8 +419,8 @@ end
begin
option_parser.parse!(into: options)
rescue OptionParser::InvalidOption => error
puts error.message
rescue OptionParser::InvalidOption => e
puts e.message
puts option_parser.help
exit 1
end

View File

@ -76,8 +76,8 @@ describe Canvas::Errors::Reporter do
def error_instance
typical_usage
rescue MyTestError => err
err
rescue MyTestError => e
e
end
def typical_usage

View File

@ -68,10 +68,10 @@ describe 'LTI Advantage Errors' do
it 'supports idiomatic raise usage' do
raise described_class, 'message override'
rescue described_class => error
expect(error.message).to eq("message override :: #{default_api_message}")
expect(error.api_message).to eq(default_api_message)
expect(error.status_code).to eq(default_status_code)
rescue described_class => e
expect(e.message).to eq("message override :: #{default_api_message}")
expect(e.api_message).to eq(default_api_message)
expect(e.status_code).to eq(default_status_code)
end
end
@ -153,10 +153,10 @@ describe 'LTI Advantage Errors' do
# LTI Advantage controllers are expected to do.)
raise Lti::IMS::AdvantageErrors::InvalidAccessTokenClaims, 'message override'
rescue Lti::IMS::AdvantageErrors::AdvantageServiceError => error
expect(error.message).to eq('message override :: Access token contains invalid claims')
expect(error.api_message).to eq('Access token contains invalid claims')
expect(error.status_code).to eq(:unauthorized)
rescue Lti::IMS::AdvantageErrors::AdvantageServiceError => e
expect(e.message).to eq('message override :: Access token contains invalid claims')
expect(e.api_message).to eq('Access token contains invalid claims')
expect(e.status_code).to eq(:unauthorized)
end
end
end

View File

@ -57,8 +57,8 @@ describe SupportHelpers::Fixer do
expect(Mailer).to receive(:create_message)
begin
fixer.monitor_and_fix
rescue => error
expect(error.message).to eq 'SupportHelpers::Fixer must implement #fix'
rescue => e
expect(e.message).to eq 'SupportHelpers::Fixer must implement #fix'
end
end
end

View File

@ -244,8 +244,8 @@ module Lti
tp_json['tool_profile']['resource_handler'][0]['message'][0]['enabled_capability'] = ['Canvas.placements.invalid']
begin
tool_proxy = tool_proxy_service.process_tool_proxy_json(json: tp_json.to_json, context: account, guid: tool_proxy_guid)
rescue Lti::Errors::InvalidToolProxyError => proxy_error
puts proxy_error.message
rescue Lti::Errors::InvalidToolProxyError => e
puts e.message
end
expect(tool_proxy).to eq nil
end