From 142ae54e54ac81a0f62eaa43c3c280307cf2127a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=89tienne=20Barri=C3=A9?= Date: Fri, 22 Jan 2021 16:07:53 -0500 Subject: [PATCH] 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 --- activejob/CHANGELOG.md | 2 ++ activejob/lib/active_job/execution.rb | 2 +- activejob/test/cases/rescue_test.rb | 5 +++++ activejob/test/jobs/rescue_job.rb | 6 ++++++ 4 files changed, 14 insertions(+), 1 deletion(-) diff --git a/activejob/CHANGELOG.md b/activejob/CHANGELOG.md index a0750a6b615..383abb4d64a 100644 --- a/activejob/CHANGELOG.md +++ b/activejob/CHANGELOG.md @@ -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. diff --git a/activejob/lib/active_job/execution.rb b/activejob/lib/active_job/execution.rb index 7594170d5e2..fc9338a3830 100644 --- a/activejob/lib/active_job/execution.rb +++ b/activejob/lib/active_job/execution.rb @@ -47,7 +47,7 @@ module ActiveJob run_callbacks :perform do perform(*arguments) end - rescue => exception + rescue Exception => exception rescue_with_handler(exception) || raise end diff --git a/activejob/test/cases/rescue_test.rb b/activejob/test/cases/rescue_test.rb index f4a6a3a065c..56cdbd61a8d 100644 --- a/activejob/test/cases/rescue_test.rb +++ b/activejob/test/cases/rescue_test.rb @@ -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 diff --git a/activejob/test/jobs/rescue_job.rb b/activejob/test/jobs/rescue_job.rb index 049a8d9adf0..00538739955 100644 --- a/activejob/test/jobs/rescue_job.rb +++ b/activejob/test/jobs/rescue_job.rb @@ -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