mirror of
https://github.com/discourse/discourse.git
synced 2025-06-04 23:36:11 +08:00
DEV: Add a try
step to services
This patch adds a new step to services named `try`. It’s useful to rescue exceptions that some steps could raise. That way, if an exception is caught, the service will stop its execution and can be inspected like with any other steps. Just wrap the steps that can raise with a `try` block: ```ruby try do step :step_that_can_raise step :another_step_that_can_raise end ``` By default, `try` will catch any exception inheriting from `StandardError`, but we can specify what exceptions to catch: ```ruby try(ArgumentError, RuntimeError) do step :will_raise end ``` An outcome matcher has been added: `on_exceptions`. By default it will be executed for any exception caught by the `try` step. Here also, we can specify what exceptions to catch: ```ruby on_exceptions(ArgumentError, RuntimeError) do |exception| … end ``` Finally, an RSpec matcher has been added: ```ruby it { is_expected.to fail_with_exception } # or it { is_expected.to fail_with_exception(ArgumentError) } ```
This commit is contained in:

committed by
Loïc Guitaut

parent
682e8df007
commit
719457e430
@ -147,6 +147,26 @@ RSpec.describe Service::Runner do
|
||||
end
|
||||
end
|
||||
|
||||
class FailureTryService
|
||||
include Service::Base
|
||||
|
||||
try { step :raising_step }
|
||||
|
||||
def raising_step
|
||||
raise "BOOM"
|
||||
end
|
||||
end
|
||||
|
||||
class SuccessTryService
|
||||
include Service::Base
|
||||
|
||||
try { step :non_raising_step }
|
||||
|
||||
def non_raising_step
|
||||
true
|
||||
end
|
||||
end
|
||||
|
||||
describe ".call" do
|
||||
subject(:runner) { described_class.call(service, dependencies, &actions_block) }
|
||||
|
||||
@ -429,6 +449,30 @@ RSpec.describe Service::Runner do
|
||||
end
|
||||
end
|
||||
|
||||
context "when using the on_exceptions action" do
|
||||
let(:actions) { <<-BLOCK }
|
||||
proc do |result|
|
||||
on_exceptions { |exception| exception.message == "BOOM" }
|
||||
end
|
||||
BLOCK
|
||||
|
||||
context "when the service fails" do
|
||||
let(:service) { FailureTryService }
|
||||
|
||||
it "runs the provided block" do
|
||||
expect(runner).to be true
|
||||
end
|
||||
end
|
||||
|
||||
context "when the service does not fail" do
|
||||
let(:service) { SuccessTryService }
|
||||
|
||||
it "does not run the provided block" do
|
||||
expect(runner).not_to eq true
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
context "when using several actions together" do
|
||||
let(:service) { FailureService }
|
||||
let(:actions) { <<-BLOCK }
|
||||
|
Reference in New Issue
Block a user