Allow jobs to rescue all exceptions

Before this commit, only StandardError exceptions can be handled by
rescue_from handlers.

This changes the rescue clause to catch all Exception objects, allowing
rescue handlers to be defined for Exception classes not inheriting from
StandardError.

This means that rescue handlers that are rescuing Exceptions outside of
StandardError exceptions may rescue exceptions that were not being
rescued before this change.

Co-authored-by: Adrianna Chang <adrianna.chang@shopify.com>
This commit is contained in:
Étienne Barrié 2021-01-22 16:07:53 -05:00
parent c9e4af5c9d
commit 142ae54e54
4 changed files with 14 additions and 1 deletions

View File

@ -1,4 +1,6 @@
* Allow `rescue_from` to rescue all exceptions.
*Adrianna Chang*, *Étienne Barrié*
Please check [6-1-stable](https://github.com/rails/rails/blob/6-1-stable/activejob/CHANGELOG.md) for previous changes.

View File

@ -47,7 +47,7 @@ module ActiveJob
run_callbacks :perform do
perform(*arguments)
end
rescue => exception
rescue Exception => exception
rescue_with_handler(exception) || raise
end

View File

@ -33,4 +33,9 @@ class RescueTest < ActiveSupport::TestCase
RescueJob.perform_later [Person.new(404)]
assert_includes JobBuffer.values, "DeserializationError original exception was Person::RecordNotFound"
end
test "rescue from exceptions that don't inherit from StandardError" do
RescueJob.perform_later("rafael")
assert_equal ["rescued from NotImplementedError"], JobBuffer.values
end
end

View File

@ -18,12 +18,18 @@ class RescueJob < ActiveJob::Base
JobBuffer.add("DeserializationError original exception was #{e.cause.class.name}")
end
rescue_from(NotImplementedError) do
JobBuffer.add("rescued from NotImplementedError")
end
def perform(person = "david")
case person
when "david"
raise ArgumentError, "Hair too good"
when "other"
raise OtherError, "Bad hair"
when "rafael"
raise NotImplementedError, "Hair is just perfect"
else
JobBuffer.add("performed beautifully")
end