Skip to content

A platform for community discussion. Free, open, simple.

DEV: Allow to filter backtrace in exceptions caught in services (#37382)

Loïc Guitautaaadd986030e
diff --git a/lib/service/base.rb b/lib/service/base.rb
index 48bfc0a4799..3dd98571393 100644
--- a/lib/service/base.rb
+++ b/lib/service/base.rb
@@ -331,6 +331,18 @@ module Service
# @!visibility private
class TryStep < Step
+ module FilteredBacktrace
+ def filtered_backtrace
+ Array
+ .wrap(backtrace)
+ .chunk { _1.match?(%r{/(gems|lib/service|ruby)/}) }
+ .flat_map do |excluded, lines|
+ next "(#{lines.size} framework line(s) excluded)" if excluded
+ lines
+ end
+ end
+ end
+
include StepsHelpers
attr_reader :steps, :exceptions
@@ -349,6 +361,7 @@ module Service
end
rescue *exceptions => e
raise e if e.is_a?(Failure)
+ e.singleton_class.prepend(FilteredBacktrace)
context[@current_step.result_key].fail(raised_exception?: true, exception: e)
context[result_key][:exception] = e
context.fail!
diff --git a/spec/lib/service/runner_spec.rb b/spec/lib/service/runner_spec.rb
index bf1a54b654d..4aa0c9d4103 100644
--- a/spec/lib/service/runner_spec.rb
+++ b/spec/lib/service/runner_spec.rb
@@ -466,7 +466,7 @@ RSpec.describe Service::Runner do
context "when using the on_exceptions action" do
let(:actions) { <<-BLOCK }
proc do |result|
- on_exceptions { |exception| exception.message == "BOOM" }
+ on_exceptions { |exception| exception }
end
BLOCK
@@ -474,7 +474,13 @@ RSpec.describe Service::Runner do
let(:service) { FailureTryService }
it "runs the provided block" do
- expect(runner).to be true
+ expect(runner).to be_a RuntimeError
+ end
+
+ context "when accessing the exception object" do
+ it "has access to a filtered backtrace" do
+ expect(runner.filtered_backtrace.size).to be < runner.backtrace.size
+ end
end
end
@@ -482,7 +488,7 @@ RSpec.describe Service::Runner do
let(:service) { SuccessTryService }
it "does not run the provided block" do
- expect(runner).not_to eq true
+ expect(runner).not_to be_a RuntimeError
end
end
end